iOS之数据本地持久化

2018-03-15  本文已影响0人  小篆风

前言

// 获取Documents路径
 NSString*docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) firstObject];

//获取Library的路径
 NSString*libDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES) lastObject];

// 获取cache路径
 NSString*cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];

// 获取tmp路径
 NSString*tmpDir =NSTemporaryDirectory();


本地数据五种持久化方式

1. NSUserDefaults

   //创建
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   //NSUserDefaults中有不同类型的存储方式,可以选择对应的方法。
   [defaults setObject:@"李四" forKey:@"name"];
   [defaults setInteger:18 forKey:@"age"];
   
   UIImage *headImg = [UIImage imageNamed:@"img"];
   NSData *data = UIImageJPEGRepresentation(headImg,100);
   [defaults setObject:data forKey:@"headImg"];
   
   //(强制存储)数据同步到文件里,防止意外退出没有存储上
   [defaults synchronize];
   
   //读取
   NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
   NSString *name = [def objectForKey:@"name"];
   NSInteger age = [def integerForKey:@"age"];
   //删除
   [def removeObjectForKey:@"headImg"];

2.plist

    /*** 写入 ***/
    //获取沙盒文件目录
     NSString *path= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    //拼接路径,这一步,沙盒中并不会存在`123.plist`文件
     NSString *fileName = [path stringByAppendingPathComponent:@ "123.plist" ];
     
     NSDictionary*dict =@{@"age":@18,@"name":@"李四"};
     
    //写入后,再次打开沙盒会发现有了`123.plist`文件
    [dict writeToFile:fileName atomically:YES];
    
    /*** 读取 ***/
    //获取`plist`路径
     NSFileManager * defaultManager = [NSFileManager defaultManager];
     NSURL * documentPath = [[defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]firstObject];
     NSString * fileSavePath = [documentPath.path stringByAppendingPathComponent:@"123.plist"];

   //存的是字典用字典读取,存的是数组用数组读取
     NSDictionary * dic = [NSDictionary dictionaryWithContentsOfFile:fileSavePath];
    

3.NSKeyedArchiver(归档)

    @interface Person : NSObject<NSCoding>

    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, copy) NSString *age;
    @property (nonatomic, copy) NSString *sex;

    @end

    @implementation Person

    - (void)encodeWithCoder:(NSCoder *)aCoder
    {
     //强调 如果是子类,继承了其他类,父类也要遵循协议执行下面代码
     //[super encodeWithCode:encode]
    
     //编码
     [aCoder encodeObject:self.name forKey:@"name"];
      [aCoder encodeObject:self.age forKey:@"age"];
      [aCoder encodeObject:self.sex forKey:@"sex"];
}

    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
    {
    //强调 如果是子类,继承了其他类,父类也要遵循协议执行下面代码
    //self = [super initWithCoder:decoder]
    
    
    //解码
      if (self = [super init])
     {
         self.name = [aDecoder decodeObjectForKey:@"name"];
         self.age = [aDecoder decodeObjectForKey:@"age"];
         self.sex = [aDecoder decodeObjectForKey:@"sex"];
     }
    
        return self;
    }

    @end
     Person *p = [[Person alloc] init];
     p.name = @"王三口";
     p.age = @"12";
     p.sex = @"男";
    
    //写入
     NSString *file =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];
     [NSKeyedArchiver archiveRootObject:p toFile:file];
    
    //读取
     NSString *filePath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];
     Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:file];

4.SQLite3

FMDB一个很好的管理SQLite的第三方库。FMDB使用可以参考 https://www.jianshu.com/p/54e74ce87404

*代码

  //打开路径
    NSString *fileName = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"text.sqlite"];
    
    //创建(打开)数据库 (如果数据库不存在,会自动创建)
    int result = sqlite3_open(fileName.UTF8String, &_db);
    
    //表示打开数据库成功
    if (result == SQLITE_OK) {
        
        const char *sql = "create table if not exists person (sex text, name text, age integer);";
        
        char *error = NULL;//错误信息
        
//         sqlite3_exec()可以执行任何SQL语句,比如创表、更新、插入和删除操作。
        int tableResult = sqlite3_exec(_db, sql, NULL, NULL, &error);
        
        //sqlite3_prepare_v2检测SQL语句的合法性,用于查询
//        sqlite3_stmt *stmt = NULL;//定义一个stmt存放结果集
//        int tableResult = sqlite3_prepare_v2(_db, sql, -1, &stmt, NULL);
        
        //增删改查都需要判断
        if (tableResult == SQLITE_OK) {
            NSLog(@"成功表创建");
        }else {
            NSLog(@"创建失败:%s",error);
        }
        
    }

5.CoreData

本编是作者君第一次发文,希望能帮大家。还有一点就是通过这样来巩固一下自己的知识。

上一篇下一篇

猜你喜欢

热点阅读