归档和解档

2016-09-23  本文已影响8人  Dove_Q

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);
}
上一篇下一篇

猜你喜欢

热点阅读