我正在创建一个需要使用类别的应用程序。将有一个我想与应用程序一起提供的基本类别集,但它可以由用户编辑(删除、添加类别)。基本的 .plist 不会被更改,而只会读取一次,然后可变地存储在其他地方。
这是我的方法:
随应用程序提供的默认类别categoryCollection.plist
。
defaultCategories.plist
将是被操纵的新 .plist 文件
categoryCollection.plist
将类别读入NSMutableSet
我使用:
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"defaultCategories"];
NSDictionary * dict = [[NSDictionary alloc]initWithContentsOfFile:dictPath];
// testing if the file has values, if not load from categoryCollection.plist
if (dict.count == 0) {
NSString *tempPath = [[NSBundle mainBundle] pathForResource:@"categoryCollection" ofType:@"plist"];
dict = [NSMutableDictionary dictionaryWithContentsOfFile:tempPath];
[dict writeToFile:dictPath atomically:YES];
}
// load into NSMutableSet
[self.stringsCollection addObjectsFromArray:[[dict objectForKey:@"categories"]objectForKey:@"default"]];
添加一个类别我称之为这个函数:
-(void)addCategoryWithName:(NSString *)name{
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"defaultCategories"];
NSMutableDictionary * dict = [[NSMutableDictionary alloc]initWithContentsOfFile:dictPath];
[[[dict objectForKey:@"categories"]objectForKey:@"default"]addObject:name];
[dict writeToFile:dictPath atomically:YES];
self.needsToUpdateCategoryCollection = YES;
}
并删除我使用的字符串:
-(void)removeCategoryWithName:(NSString *)name{
NSString *mainBundlePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *dictPath = [mainBundlePath stringByAppendingPathComponent:@"defaultCategories"];
NSDictionary * dict = [[NSDictionary alloc]initWithContentsOfFile:dictPath];
NSMutableArray *temp = [NSMutableArray arrayWithArray:[[dict objectForKey:@"categories"]objectForKey:@"default"]] ;
for (NSString *string in temp) {
if ([string isEqualToString:name]) {
[temp removeObject:string];
break;
}
}
[[dict objectForKey:@"categories"]removeObjectForKey:@"default"];
[[dict objectForKey:@"categories"] setValue:temp forKey:@"default"];
[dict writeToFile:dictPath atomically:YES];
self.needsToUpdateCategoryCollection = YES;
}
代码实际上工作得很好,但我想知道是否真的需要大量 I/O 操作、测试等开销,或者是否有更优雅的解决方案来存储字符串集合并让它们被操纵?
或者,如果您看到任何可能提高速度的减速带(因为当有很多类别时,我的代码会有一些小的滞后)
有什么想法吗?塞巴斯蒂安