6

我正在开发和应用程序,它需要检查字符串是否已保存到数据库中。这似乎是一个简单的操作,但它需要半秒钟才能返回任何我认为很多的响应。我的问题是是否有任何方法可以减少该时间。感谢您的关注。

这是我当前的代码:

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

}
4

1 回答 1

6

一种优化是替换

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

经过

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

如果您只想检查对象是否存在。

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

与其将状态和图片编号存储在一个属性中(如您在评论中所写) ,deleted.<status>.<picturenumber>不如在实体中使用单独的属性。statuspicturenumber

然后可以用谓词搜索图片编号

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

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

于 2013-03-03T23:03:56.613 回答