【发布时间】:2010-09-26 12:46:05
【问题描述】:
我正在为我的应用程序构建一个插件,用户可以在其中搜索列表中的项目,该列表中预先填充了来自 .plist 文件的数据。它是一个 NSDictionary。如果用户搜索的词不存在,用户可以点击 + 按钮并添加它,以便下次出现。
首先我认为它就像使用 NSUserDefaults 一样简单,但出现了一些问题。
要包含列表,我必须将其放入捆绑包中,但如果存在,我无法向其中添加新的键/值对。我只能对位于 Documents 文件夹中的文件执行此操作。
所以我想我必须捆绑 plist,然后在第一次运行时将它移动到文档文件夹并在那里访问它。
当我需要更新应用程序时,这会引发问题,我猜它会覆盖用户输入的值。
是否有一种安全、易于理解、正确的方法来实现我描述的功能?
感谢您提供的任何帮助:)
编辑:**** TheSquad 和 TomH 建议的实际方法*****
+ (NSMutableDictionary*) genericProducts {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"GenericProducts.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:@"GenericProducts.plist"];
if([fileManager fileExistsAtPath:documentPlistPath]){
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
} else {
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success) {
NSMutableDictionary *newlySavedDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return newlySavedDict;
}
return nil;
}
}
以及将新产品添加到列表中:
+ (void) addItemToGenericProducts:(NSString*) newProduct {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:@"GenericProducts.plist"];
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
[documentDict setObject:newProduct forKey:[MD5Checksum cheksum:newProduct]];
[documentDict writeToFile:documentPlistPath atomically:YES];
}
【问题讨论】:
标签: iphone plist nsdictionary