核心数据获取请求优化

IOS*_*DEV 6 optimization core-data objective-c nsfetchrequest ios

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

这是我目前的代码:

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

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 6

一个优化是替换

NSArray *objects = [context executeFetchRequest:request error:&error];
Run Code Online (Sandbox Code Playgroud)

通过

[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
Run Code Online (Sandbox Code Playgroud)

如果你只想检查对象的存在.

但我认为主要的性能问题是使用通配符搜索LIKE,这比搜索速度慢==.

而不是将状态和图片编号存储在一个属性中deleted.<status>.<picturenumber>(如您在评论中所写)status,picturenumber在实体中使用单独的属性可能更好.

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

[NSPredicate predicateWithFormat:@"picturenumber == %d", i];
Run Code Online (Sandbox Code Playgroud)

哪个应该快得多.如有必要,您还可以索引该属性(如注释中提到的@flexaddicted).