- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = @"abc";
[NSKeyedArchiver archiveRootObject:str toFile:@"/Users/apple/Desktop/test.plist"];
NSString *str1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/apple/Desktop/test.plist"];
NSLog(@"%@", str1);
Student *stu = [[Student alloc] init];
stu.name = @"Zhangsan";
stu.age = 30;
[NSKeyedArchiver archiveRootObject:stu toFile:@"/Users/apple/Desktop/student.plist"];
Student *stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/apple/Desktop/student.plist"];
NSLog(@"%p, %p", stu, stu1);
NSLog(@"%@:%d, %@:%d", stu.name, stu.age, stu1.name, stu1.age);
NSData *stuData = [NSKeyedArchiver archivedDataWithRootObject:stu];
[stuData writeToFile:@"/Users/apple/Desktop/stu.plist" atomically:YES];
NSData *stuData2 = [NSData dataWithContentsOfFile:@"/Users/apple/Desktop/stu.plist"];
Student *stu3 = [NSKeyedUnarchiver unarchiveObjectWithData:stuData2];
NSLog(@"%@:%d---%@:%d", stu.name, stu.age, stu3.name, stu3.age);
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:stuData forKey:@"xxxx"];
NSData *stuData3 = [userDefault objectForKey:@"xxxx"];
Student *stu4 = [NSKeyedUnarchiver unarchiveObjectWithData:stuData3];
NSLog(@"%@:%d", stu4.name, stu4.age);
stu4.dog = [[Dog alloc] init];
stu4.dog.name = @"小強";
[NSKeyedArchiver archiveRootObject:stu4 toFile:@"/Users/apple/Desktop/dog.plist"];
}
要記住一點的就是,當對自定義的類使用歸檔的話,必須除了先協議委託<NScoding>這個協議之外,同時在.m中實現NScoding中的兩個required方法
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:kNameKey];
[aCoder encodeInteger:_age forKey:kAgeKey];
[aCoder encodeObject:_dog forKey:kDogKey];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:kNameKey];
self.age = [aDecoder decodeIntegerForKey:kAgeKey];
self.dog = [aDecoder decodeObjectForKey:kDogKey];
}
return self;
}