[英]Core Data fetch request optimization
我正在开发和应用程序,需要检查字符串是否已保存到数据库。 这似乎是一个简单的操作,但它需要半秒才能返回任何我认为非常多的响应。 我的问题是,是否有任何方法可以缩短时间。 谢谢你的关注。
这是我目前的代码:
- (BOOL) isDeleted:(int)i {
NSString *value = [NSString stringWithFormat:@"deleted.*.%i", i];
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSString *entityName = @"Deleted";
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(deletedpics like %@)", value];
[request setPredicate:pred];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
BOOL returnBool = [objects count] >= 1 ? YES : NO;
return returnBool;
}
一个优化是替换
NSArray *objects = [context executeFetchRequest:request error:&error];
通过
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
如果你只想检查对象的存在。
但我认为主要的性能问题是使用LIKE
进行通配符搜索,这比使用==
搜索要慢。
而不是将状态和图片编号存储在一个属性中作为deleted.<status>.<picturenumber>
(正如您在评论中所写),在实体中使用单独的属性status
和picturenumber
可能更好。
然后,您可以使用谓词搜索图片编号
[NSPredicate predicateWithFormat:@"picturenumber == %d", i];
哪个应该快得多。 如有必要,您还可以索引该属性(如注释中提到的@flexaddicted)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.