NSUserDefaults
旨在满足用户偏好,而不是存储应用程序数据。使用CoreData或将对象序列化到文档目录中。你需要让你的类实现NSCoding
协议才能工作。
1)NSCoding
实施Occasion.h
@interface Occasion : NSObject <NSCoding>
2) 实现协议Occasion.m
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.date = [aDecoder decodeObjectForKey:@"date"];
self.imagePath = [aDecoder decodeObjectForKey:@"imagePath"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:title forKey:@"title"];
[aCoder encodeObject:date forKey:@"date"];
[aCoder encodeObject:imagePath forKey:@"imagePath"];
}
3) 将数据归档到文档目录中的文件中
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *path= [documentsPath stringByAppendingPathComponent:@“occasions”];
[NSKeyedArchiver archiveRootObject:occasions toFile:path];
4) 取消归档...
NSMutableArray *occasions = [NSKeyedUnarchiver unarchiveObjectWithFile:path];