2013-03-03 132 views
5

我正在开发和应用程序需要检查一个字符串是否已被保存到数据库中。这似乎是一个简单的操作,但它需要半秒钟才能返回我认为相当多的任何响应。我的问题是,如果有什么方法可以缩短这个时间。感谢您的关注。核心数据获取请求优化

这是我当前的代码:

- (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; 

} 
+0

你能解释实体和关系吗?我不太了解谓词。 – 2013-03-03 20:06:50

+0

不同实体之间没有关系。具体而言,该实体只包含一个名为_deletedpics_的属性。参照谓词,这个想法是检查图片是否已被报告为已删除或未被删除。我将删除的寄存器组织为“deleted.status(我需要用于其他操作的变量).picturenumber”。在这个功能中,我想检查某个图片是否被删除或没有考虑到状态。这就是我使用这个谓词的原因。我希望现在更清楚。 – 2013-03-03 20:26:34

+0

尝试索引该属性。 “@”删除了什么?*。%i“'是什么意思? – 2013-03-03 21:11:37

回答

5

一种优化是

[request setFetchLimit:1]; 
NSUInteger count = [context countForFetchRequest:request error:&error]; 

更换

NSArray *objects = [context executeFetchRequest:request error:&error]; 

,如果你只是想检查对象的存在。

但我认为主要的性能问题是LIKE的通配符搜索,这比搜索==慢。

不是存储状态和一个 属性为deleted.<status>.<picturenumber>图片编号(如你在评论中写道),它可能会更好地使用单独的属性status,并在实体picturenumber的。

然后你就可以搜索图片数量与谓词

[NSPredicate predicateWithFormat:@"picturenumber == %d", i]; 

这应该是要快得多。如有必要,您可以额外索引该属性(如评论中提到的@flexaddicted)。

+0

+1我没有时间回复,但你的回复很好。感谢您引用了我的评论。 – 2013-03-03 23:15:15

+0

@flexaddicted:谢谢:-) – 2013-03-03 23:20:00