- 归档反归档是数据存储方式的一种。归档将复杂数据结构转换成NSData进行存储,反归档将NSData转成复杂数据结构。
存储自定义类型,需要先服从“<NSCoding>”协议,然后实现两个方法:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (instancetype)initWithCoder:(NSCoder *)aDecoder;
⚠️:如果有一个(类A)继承(Model),那么(类A)也需要实现这两个方法。
⚠️:在真机上测试的时候,一要给plist文件写一个明确的地址,不能只给个沙盒文件路径。
----------------------------------Model.h-----------------------------------
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface Model : NSObject<NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, strong) UIImage *image;
- (NSString *)description;
@end
---------------------------------------Model.m-----------------------------
#import "Model.h"
@implementation Model
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:UIImagePNGRepresentation(self.image) forKey:@"image"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];;
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.image = [aDecoder decodeObjectForKey:@"image"];
}
return self;
}
- (NSString *)description
{
NSString *string = [NSString stringWithFormat:@"%@,%ld,%@",self.name,(long)self.age, self.image];
return string;
}
Model *modelPanda = [[Model alloc] init];
modelPanda.name = @"panda";
modelPanda.age = 18;
modelPanda.image = [UIImage imageNamed:@"123.jpg"];
Model *modelLuce = [[Model alloc] init];
modelLuce.name = @"Luce";
modelLuce.age = 20;
modelLuce.image = [UIImage imageNamed:@"123.jpg"];
NSMutableArray *arr = [@[modelLuce, modelPanda] mutableCopy];
//真机时候,要将@"path.plist" -> @"Documents/pers.plist";
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"path.plist"];
NSMutableData *mulData = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mulData];
[archiver encodeObject:arr forKey:@"arr"];
[archiver finishEncoding];
BOOL success = [mulData writeToFile:path atomically:YES];
NSLog(@"%d", success);
//反归档
NSData *data = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
id arrUN = [unarchiver decodeObjectForKey:@"arr"];
NSLog(@"%@", arrUN);
//归档
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"person.plist"];
BOOL success = [NSKeyedArchiver archiveRootObject:modelLuce toFile:filePath];
NSLog(@"success : %d", success);
//反归档
Model *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@", person);
当属性较多时可以利用runtime进行归档反归档。
待实现...
参考:http://blog.csdn.net/xuejunrong/article/details/51771158
http://stackoverflow.com/questions/963175/nskeyedarchiver-works-in-iphone-simulator-fails-on-device
网友评论