有用的总结iOS学习笔记iOS开发记录

iOS本地数据持久化

2016-01-20  本文已影响292人  论丶道

在iOS开发中常常需要将本地数据存储起来 通常有如下几种方式

    NSArray *array = @[@"jack",@26];
    //获取caches文件夹路径
    //NSSearchPathDirectory directory -->搜索文件夹
    //NSSearchPathDomainMask domainMask -->在哪个范围内查找
    //BOOL expandTilde -->是否展开
   NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    //拼接文件名
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"array.plist"];
    //存储数据
    [array writeToFile:filePath atomically:YES];
- plist存储的数据读取(比如想要读取一个数组)
    //获取caches文件夹路径
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    //拼接文件名
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"array.plist"];
    //读取文件
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"jack" forKey:@"name"];
    [defaults setInteger:26 forKey:@"age"];
- 偏好设置读取
NSString *name = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    NSInteger age = [[NSUserDefaults standardUserDefaults] integerForKey:@"age"];
ZDCar *car = [[ZDCar alloc] init];
    car.brand = @"BMW";
    car.color = @"black";
    //获取caches文件夹
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    //拼接文件名
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"car.xxoo"];
    //存储数据
    [NSKeyedArchiver archiveRootObject:car toFile:filePath];
- 归档存储的读取
//获取caches文件夹
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    //拼接文件名
    NSString *filePath = [cachesPath stringByAppendingPathComponent:@"car.xxoo"];
    //读取数据
    ZDCar *car = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

注意:在调用
[NSKeyedArchiver archiveRootObject:car toFile:filePath];和[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];这两个方法时
底层会调用
- (void)encodeWithCoder:(NSCoder *)aCoder
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder这两个方法 所以需要在自定义的类中遵守<NSCoding>这个协议并实现上述两个方法
还有一点需要注意 在实现- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder这个方法时当父类遵守了<NSCoding>这个协议就需要调用[super initWithCoder:aDecoder] 反之则调用[super init]

上一篇 下一篇

猜你喜欢

热点阅读