使用NSKeyedArchiver归档
NSDictionary *writedic = @{@"key1":@"value1",@"key2":@"value2",@"key3":@"value3"}; [NSKeyedArchiver archiveRootObject:writedic toFile:@"mydic.archive"]; NSDictionary *readdic = [NSKeyedUnarchiver unarchiveObjectWithFile:@"mydic.archive"]; NSLog(@"%@",readdic);
使用NSCoding对自定义对象归档
1类定义
@interface Zltobject : NSObject<NSCoding> { NSString *_name; int _age; float _weight; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_name forKey:@"name"]; [aCoder encodeInt:_age forKey:@"age"]; [aCoder encodeFloat:_weight forKey:@"weight"]; } - (id)initWithCoder:(NSCoder *)aDecoder { _name = [aDecoder decodeObjectForKey:@"name"]; _age = [aDecoder decodeIntForKey:@"age"]; _weight = [aDecoder decodeFloatForKey:@"weight"]; return self; }
2归档
Zltobject *obj = [[Zltobject alloc] initWithName:@"zlt" Age:18 Weight:120.5]; [NSKeyedArchiver archiveRootObject:obj toFile:@"obj.archive"]; Zltobject *obj2 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"obj.archive"]; NSLog(@"%@",obj2);
如果类中的成员变量有其他的自定义类,也需要实现NSCoding协议
使用NSData归档多个对象
NSDictionary *archive1 = @{@"key1":@"value1"}; Zltobject *archive2 = [[Zltobject alloc] initWithName:@"zlt" Age:18 Weight:120.5]; NSMutableData *writeData = [NSMutableData data]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:writeData]; [archiver encodeObject:archive1 forKey:@"archive1"]; [archiver encodeObject:archive2 forKey:@"archive2"]; //结束归档 [archiver finishEncoding]; //写入文件 [writeData writeToFile:@"mutable.archive" atomically:YES]; NSData *readData = [NSData dataWithContentsOfFile:@"mutable.archive"]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:readData]; NSDictionary *dic = [unarchiver decodeObjectForKey:@"archive1"]; Zltobject *zltobj = [unarchiver decodeObjectForKey:@"archive2"]; //结束恢复 [unarchiver finishDecoding]; NSLog(@"%@,%@",dic,zltobj);