在日常开发中对于NSString、NSDictionary、NSArray、NSData、NSNumber这些基本类的数据持久化,可以用属性列表的方法持久化到.plist 文件中。但是一些我们自定义的类的话,属性列表的方法就不能用了,这时候是NSKeyedArchiver出马的时候了。以我们前面写的Person 类为例,看NSKeyedArchiver 如何一展身手。
Person 类
////////////////// .h //////////////// #import <Foundation/Foundation.h> @interface Person : NSObject<NSCoding> @property (nonatomic,copy)NSString *name; @property (nonatomic,assign)int age; @property (nonatomic,copy)NSString *sex; - (void)printInfo; @end ////////////////// .m //////////////// #import "Person.h" @implementation Person @synthesize name = _name,sex = _sex; @synthesize age = _age; //写入文件 -(void)encodeWithCoder:(NSCoder *)encoder{ [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeObject:self.name forKey:@"name"]; [encoder encodeObject:self.sex forKey:@"sex"]; } //从文件中读取 -(id)initWithCoder:(NSCoder *)decoder{ self.age = [decoder decodeIntForKey:@"age"]; self.name = [decoder decodeObjectForKey:@"name"]; self.sex = [decoder decodeObjectForKey:@"sex"]; return self; } - (void)printInfo { NSLog(@"我的名字叫:%@ 今年%d岁 我是一名%@ %@",self.name,self.age,self.sex,NSStringFromClass([self class])); } @end
AppDelegate.m 中测试
#import "AppDelegate.h" #import "Person.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { Person *person = [[[Person alloc] init] autorelease]; person.age = 18; person.sex = @"男"; person.name = @"SuperDo.Horse"; //获得Document的路径 NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [documents stringByAppendingPathComponent:@"person.archiver"];//拓展名可以自定义 [NSKeyedArchiver archiveRootObject:person toFile:path]; Person *person2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; [person2 printInfo]; return YES; } @end
打印结果:
2015-07-05 22:37:48.876 Attendance[80142:2069100] 我的名字叫:SuperDo.Horse 今年18岁我是一名男 Person
本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 )
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4623177.html