【发布时间】:2010-09-29 14:22:29
【问题描述】:
我正在创建一个 iphone/ipad 应用程序,它基本上读取 XML 文档并从基于 xml 创建的对象创建表视图。 xml 代表文件系统中的“级别”。它基本上是一个浏览器。
每次我解析 xml 文档时,我都会更新在核心数据 sqllite 数据库中镜像的文件系统。对于 xml 中遇到的每个“文件”,我都会尝试获取与之关联的 NSManagedObject。
问题是我用来获取/创建一个新的空白实体或从数据库中获取现有实体的这个函数。
+(File*)getOrCreateFile:(NSString*)remotePath
context:(NSManagedObjectContext*)context
{
struct timeval start,end,res;
gettimeofday(&start,NULL);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
[fetchRequest setFetchLimit:1];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remotePath == %@",remotePath];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
File *f;
if ([items count] == 0)
f = (File*)[NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:context];
else
f = (File*)[items objectAtIndex:0];
gettimeofday(&end, NULL);
[JFS timeval_subtract:&res x:&end y:&start];
count++;
elapsed += res.tv_usec;
return f;
}
对于 eksample,如果我正在解析包含 200 个文件的文档,则在 iPhone 3G 上的总时间约为 4 秒。其中 3 秒用于此函数从核心数据中获取对象。
RemotePath 是可变长度的唯一字符串,并在 sqllite 数据库中建立索引。
我在这里做错了什么?或者..我可以做些什么更好/不同来提高性能。
【问题讨论】:
标签: performance core-data