我一直在使用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