美文网首页
归档和解档

归档和解档

作者: Dove_Q | 来源:发表于2016-09-23 15:10 被阅读8次

    Animal.m

    #import "Animal.h"
    
    @interface Animal ()<NSCoding>
    
    @end
    
    @implementation Animal
    
    -(instancetype)initWithCoder:(NSCoder *)aDecoder {
        self = [super init];
        if (self) {
            self.name = [aDecoder decodeObjectForKey:@"kname"];
        }
        return self;
    }
    - (void)encodeWithCoder:(NSCoder *)aCoder {
        [aCoder encodeObject:self.name forKey:@"kname"];
    }
    @end
    

    ViewController

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        Animal *ani = [Animal new];
        ani.name = @"animal_name";
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ani.plist"];
        NSLog(@"%@", path);
        //第一次没有创建文件
        if (![NSKeyedUnarchiver unarchiveObjectWithFile:path]) {
            [NSKeyedArchiver archiveRootObject:and toFile:path];
        }
        [NSKeyedArchiver archiveRootObject:ani toFile:path];
        
        Animal *ani2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"----->%@", ani2.name);
    }
    

    相关文章

      网友评论

          本文标题:归档和解档

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