【发布时间】:2009-08-05 22:34:48
【问题描述】:
我正在开发一个从数据库中获取大量对象的 iPhone 应用程序。我想使用 Core Data 来存储这些,但我的关系有问题。
一个详细信息包含任意数量的 POI(兴趣点)。当我从服务器获取一组 POI 时,它们包含一个详细 ID。为了将 POI 与 Detail 关联(按 ID),我的过程如下: 在 ManagedObjectContext 中查询 detailID。 如果该详细信息存在,请将 poi 添加到其中。 如果没有,请创建详细信息(它还有其他将延迟填充的属性)。
问题在于性能。由于涉及到多个关系,对 Core Data 执行持续查询很慢,以至于添加 150 个 POI 的列表需要一分钟。
在我的旧模型中,在 Core Data(各种 NSDictionary 缓存对象)之前,这个过程非常快(在字典中查找一个键,如果它不存在则创建它)
我的关系不止这一个,但几乎每个人都必须做这个检查(有些是多对多的,而且他们有一个真正的问题)。
有没有人对我可以如何提供帮助有任何建议?我可以执行更少的查询(通过搜索多个不同的 ID),但我不确定这会有多大帮助。
一些代码:
POI *poi = [NSEntityDescription
insertNewObjectForEntityForName:@"POI"
inManagedObjectContext:[(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]];
poi.POIid = [attributeDict objectForKey:kAttributeID];
poi.detailId = [attributeDict objectForKey:kAttributeDetailID];
Detail *detail = [self findDetailForID:poi.POIid];
if(detail == nil)
{
detail = [NSEntityDescription
insertNewObjectForEntityForName:@"Detail"
inManagedObjectContext:[(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext]];
detail.title = poi.POIid;
detail.subtitle = @"";
detail.detailType = [attributeDict objectForKey:kAttributeType];
}
-(Detail*)findDetailForID:(NSString*)detailID {
NSManagedObjectContext *moc = [[UIApplication sharedApplication].delegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"Detail" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"detailid == %@", detailID];
[request setPredicate:predicate];
NSLog(@"%@", [predicate description]);
NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil || [array count] != 1)
{
// Deal with error...
return nil;
}
return [array objectAtIndex:0];
}
【问题讨论】:
-
更详细地解释您的对象,并发布您使用的一些代码。几乎 100% 可能有一种方法可以更快地完成您已经在做的事情。
标签: objective-c iphone core-data