NSUserDefaults
用于用户偏好,不存储应用程序数据。使用CoreData或将对象序列化到文档目录中。你需要让你的班级实施NSCoding
协议才能工作。
1)Occasion.h
@interface Occasion : NSObject <NSCoding>
2实施NSCoding
)在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];
感谢您的帮助。这个想法现在对我来说很清楚。最后一个问题:对于这个步骤(NSArray * myArray = [NSKeyedUnarchiver unarchiveObjectWithData:serialized];)会给我一个NSArray,而我的原始数组是一个NSMutableArray。所以我应该使用类似[复制可变]的东西? – Ali
如果它返回一个标准的'NSArray',然后使用'[array mutableCopy]'得到一个可变的版本。 –
再次感谢您的帮助。 – Ali