IOS NSKeyedArchiver(归档存取数据)

如果对象是NSStringNSDictionaryNSArrayNSDataNSNumber等类 型,可以直接用NSKeyedArchiver进行归档和恢复

不是所有的对象都可以直接用这种方法进行归档,只有遵守了NSCoding协 议的对象才可以

NSCoding协议有2个方法:

encodeWithCoder:

每次归档对象时,都会调用这个方法。一般在这个方法里面指定如何归档对象中的每个实例变量,

可以使用encodeObject:forKey:方法归档实例变量

initWithCoder:

每次从文件中恢复(解码)对象时,都会调用这个方法。一般在这个方法里面指定如何解 码文件中的数据为对象的实例变量,

可以使用decodeObject:forKey方法解码实例变量 

归档一个NSArray对象到Documents/array.archive

NSArray *array = [NSArray arrayWithObjects:@”a”,@”b”,nil];

[NSKeyedArchiver archiveRootObject:array toFile:path]; 

恢复(解码)NSArray对象 

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; 

归档(编码)
Person *person = [[[Person alloc] init] autorelease]; person.name = @"MJ";
person.age = 27;
person.height = 1.83f;
[NSKeyedArchiver archiveRootObject:person toFile:path];

恢复(解码)
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; 

NSKeyedArchiver-归档对象的注意 

如果父类也遵守了NSCoding协议,请注意:

应该在encodeWithCoder:方法中加上一句 [super encodeWithCode:encode]; 确保继承的实例变量也能被编码,即也能被归档

应该在initWithCoder:方法中加上一句 self = [super initWithCoder:decoder]; 确保继承的实例变量也能被解码,即也能被恢复 

代码:

@implementation Person
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:@"name"]; [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeFloat:self.height forKey:@"height"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self.name = [decoder decodeObjectForKey:@"name"]; self.age = [decoder decodeIntForKey:@"age"]; self.height = [decoder decodeFloatForKey:@"height"]; return self;
}
- (void)dealloc {
   [super dealloc];
   [_name release];
}
@end
View Code
- (IBAction)saveBtnClick:(id)sender;
- (IBAction)readBtnClick:(id)sender;

@end

@implementation NJViewController

- (IBAction)saveBtnClick:(id)sender {
    // 1.创建对象
    /*
    NJPerson *p = [[NJPerson alloc] init];
    p.name = @"lnj";
    p.age = 28;
    p.height = 1.76;
     */
    
    NJStudent *stu = [[NJStudent alloc] init];
    stu.name = @"lnj";
    stu.age = 28;
    stu.height = 1.8;
    stu.weight = 60;
    
    // 2.获取文件路径
    NSString *docPath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
    NSLog(@"path = %@", path);
    
    // 3.将自定义对象保存到文件中
//    [NSKeyedArchiver archiveRootObject:p toFile:path];
    [NSKeyedArchiver archiveRootObject:stu toFile:path];
    
}

- (IBAction)readBtnClick:(id)sender {
    
    // 1.获取文件路径
    NSString *docPath =  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];

    // 2.从文件中读取对象
//    NJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    NJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

    
    NSLog(@"%@ %d %.1f %.1f", stu.name, stu.age, stu.height, stu.weight);
}
View Code
原文地址:https://www.cnblogs.com/liuwj/p/6530589.html