美文网首页
简单的归档解档

简单的归档解档

作者: 3fbfd3c15df9 | 来源:发表于2017-11-14 23:42 被阅读28次

    我们想要长久保存自定义对象数据,那么就少不了对沙盒的操作。


    屏幕快照 2017-11-14 下午10.14.03.png 屏幕快照 2017-11-14 下午10.20.12.png
    获得路径的方式 Documents , Library , tmp

    Documents : iTunes 会备份,苹果也不允许保存东西在这里面。会被拒
    tmp : 临时保存,随时可能被删除
    Library : ----> 下面2个子目录
    Caches :缓存文件
    Preferences:偏好设置 保存账号等信息 --> 经过我测试 [NSUserDefaults standardUserDefaults] 就是保存在这里的

    //获取Caches路径
         NSArray *path1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        //获取Library路径
         NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        //获取Documents路径
         NSArray *path3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    关于归档具体实现1,自定义对象 2, 数组,字典的归档

    例子1:字典数组的归档

    /**
       字典的存取 沙盒路径
     */
    -(void)dicArchivie
    {
        NSString *chahe = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [chahe stringByAppendingString:@"accont.plist"];
        NSDictionary *dic = @{@"name":@"xiaoming",@"age":@"18"};
        //存
        [dic writeToFile:path atomically:YES];
        NSLog(@"paths = %@",path);
        //取
        NSDictionary *dicM = [NSDictionary dictionaryWithContentsOfFile:path];
        NSLog(@"dicM = %@",dicM);
    }
    
    /*
    @interface NSDictionary<__covariant KeyType, __covariant ObjectType> : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>
    这是字典的归档,直接归档到沙盒 cache路径文件下面
    从这里可以看出 ,要遵循 NSCoding,NSCopying 
    */
    

    例子2:自定义对象的归档解档,我们归档一个person类。

    //这是person.h
    #import <Foundation/Foundation.h>
    @interface Person : NSObject<NSCoding,NSCopying>
    @property (nonatomic,copy)NSString *name ;
    @property (nonatomic,copy)NSString *age;
    @property (nonatomic,assign)CGFloat weight;
    @end
    
    //这是person.m 实现
    #import "Person.h"
    #import <objc/runtime.h>
    @interface Person ()
    @end
    @implementation Person
     //方式 1 ,runtime 快速归档
    #if 0
    //这是runtime 的方法 NSCoding 实现归档的协议
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
        unsigned int count = 0;
        Ivar *ivars = class_copyIvarList([self class], &count); //获取所有的属性
        for (int i = 0; i<count; i++) {
            //取出变量
            Ivar ivar = ivars[i];
            //查看变量的名字
            NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
            //查看变量的类型
            //NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
            //  利用KVC取出属性对应的值
            id value = [self valueForKey:name];
            //实现归档
            [aCoder encodeObject:value forKey:name];
        }
        //  记住C语言中copy出来的要进行释放
        free(ivars);
    }
    
    //解档
    -(instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        if (self =[super init]) {
            unsigned int count = 0;
            Ivar *ivars = class_copyIvarList([self class], &count);
            for (int i = 0; i<count; i++) {
                //取出变量
                Ivar ivar = ivars[i];
                //查看变量的名字
                NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
                //取出变量的值
                id value = [aDecoder decodeObjectForKey:name];
                //KVC 赋值
                [self setValue:value forKeyPath:name];
            }
            free(ivars);
        }
        return self;
    }
    #endif
    
    //---------------------------------------------------------------------------
    //方式2
    -(void)encodeWithCoder:(NSCoder *)aCoder
    {
            [aCoder encodeObject:self.name forKey:@"name"];
            [aCoder encodeObject:self.age forKey:@"age"];
            [aCoder encodeObject:@(self.weight) forKey:@"weight"];
    }
    
    //解档
    -(instancetype)initWithCoder:(NSCoder *)aDecoder
    {
        if (self =[super init]) {
            self.name = [aDecoder decodeObjectForKey:@"name"];
            self.age = [aDecoder decodeObjectForKey:@"age"];
            self.weight = [[aDecoder decodeObjectForKey:@"weight"] doubleValue];
        }
        return self;
    }
    
    //这是ViewController 调用方法
    /**
        自定义对象的沙盒存取  NSKeyedArchiver 必须用这个
     */
    -(void)customObject
    {
        Person *p = [Person new];
        p.name = @"小明";
        p.age = @"14";
        p.weight = 55;
        
        NSString *chahe = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [chahe stringByAppendingString:@"accton.archive"];
        NSLog(@"path = %@",path) ;
        //自定义对象的存储必须用 NSKeyedArchiver  不能用 writeToFile
        //writeToFile适用 NSArray 和 NSDictionary
        [NSKeyedArchiver archiveRootObject:p toFile:path]; //自定义对象   沙盒 存
        Person *person =  [NSKeyedUnarchiver unarchiveObjectWithFile:path];// 自定义对象   沙盒 取
        NSLog(@"%@ %@ %f" ,person.name,person.age,person.weight);
            //这里copy Person 必须实现NSCoying
    //    Person *p1 = [Person mutableCopy];
    //    NSLog(@"p1.name = %@" ,p1.name);
    }
    

    Demo下载地址

    相关文章

      网友评论

          本文标题:简单的归档解档

          本文链接:https://www.haomeiwen.com/subject/ajdqvxtx.html