我一直在使用NSKeyedArchivers来存储列表。 http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSKeyedArchiver_Class/Reference/Reference.html
非常容易管理,它可以轻松地存储,保存和检索所有数据。
示例将是对象的列表(NSMutableArray)。每个对象都实现NSCoding并具有initWithCoder:和encodeWithCoder:函数。
例如(假设对象有一个名字和日期属性)
- (id) initWithCoder:(NSCoder *){
self = [super init];
if (self){
[self setName:[aDecoder decodeObjectForKey:@"name"]];
[self setDate:[aDecoder decodeObjectForKey:@"date"]];
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:name forKey:@"name"];
[aCoder encodeObject:date forKey:@"date"];
}
然后,你可以简单地让您的NSMutableArray,您就可以添加这些对象,通过一些东西,具有以下功能进行管理,只需要调用的SaveChanges:
- (NSString *) itemArchivePath{
NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [documentDirectories objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"myArchiveName.archive"];
}
- (BOOL) saveChanges{
NSString *path = [self itemArchivePath];
return [NSKeyedArchiver archiveRootObject:myList toFile:path];
}
执行这两个函数后,您可以调用saveChanges。
,并检索列表中的下一个启动后后,在经理的init:
- (id) init{
self = [super init];
if (self){
NSString *path = [self itemArchivePath];
myList = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
// If the array hadn't been saved previously, create a new empty one
if (!myList){
myList = [[NSMutableArray Alloc] init];
}
}
}
来源
2013-05-06 17:01:16
Doc
感谢您的回复,这很合理! – amitsbajaj 2013-05-09 07:53:51