对于使用Core Data的几个不同的提取重用NSFetchRequest有什么不好吗?

时间:2012-05-20 13:52:26

标签: xcode core-data nspredicate nsfetchrequest

我的问题: 使用Core Data对多个不同的提取重用NSFetchRequest有什么不好吗?

示例代码:

NSFetchRequest *request = [[NSFetchRequest alloc] init];

NSEntityDescription *logEntity = [NSEntityDescription entityForName:@"LogEntry" inManagedObjectContext:context];
[request setEntity:logEntity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateTimeAction" ascending:NO]; // ascending NO = start with latest date
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status == %@",@"op tijd"];
[request setPredicate:predicate];
[request setFetchLimit:50];

NSError *error = nil;
NSInteger onTimeCount = [context countForFetchRequest:request error:&error];

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"status == %@",@"uitgesteld"];
[request setPredicate:predicate1];
[request setFetchLimit:50];

NSInteger postponedCount = [context countForFetchRequest:request error:&error];

NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"status == %@",@"gemist"];
[request setPredicate:predicate2];
[request setFetchLimit:50];

NSInteger missedCount = [context countForFetchRequest:request error:&error];

3 个答案:

答案 0 :(得分:5)

这不是问题,但在示例中,它并没有获得太多(只是一些代码简洁。)创建获取请求最昂贵的部分是解析谓词格式字符串。

如果您经常拨打的代码被调用,并且您希望加快速度,那么可以尝试以下方法:

  • 只创建一次所有谓词和获取请求:可能在dispatch_once()块中并静态存储它们;或者在构造函数中并存储在对象字段中
  • 不指定排序描述符,因为如果您只关心计数
  • ,顺序无关紧要
  • 如果实际谓词比显示的更复杂或更灵活,请使用替换变量创建一个通用模板谓词,并使用predicateWithSubstitutionVariables:生成指定的副本。
  • 为了更加简洁,请使用模型编辑器在对象模型中定义该模板,并使用fetchRequestFromTemplateWithName:substitutionVariables:创建获取请求。

如果你愿意,我可以打开一些示例代码。

答案 1 :(得分:1)

我不认为这是一个问题,因为NSFetchedRequest只是一个搜索条件描述符,而且你可以在你提取的请求上有多个谓词,如下所示:

NSPredicate *predicates = [NSCompoundPredicate andPredicateWithSubpredicates:NSArray_of_predicates];

答案 2 :(得分:0)

如果您在同一商店或同一型号的不同商店中重复使用它们,可以。使用相同的提取请求查询具有不同模型的多个商店时,我遇到了崩溃(例如在NSKnownKeysDictionary1中)。重用请求似乎很有意义,因为我只是从两个不同的地方获取同一实体。实体名称和谓词相同。您可能会认为这是可以的,因为获取请求采用实体名称而不是实体描述。对于不同商店/模型中的同一实体,后者将是一个不同(但等效)的对象。但是,fetch请求似乎缓存了实体描述,并且没有检查它对于要针对其执行的当前上下文是否仍然有效。

但是,您可以在多个提取请求中重用相同的谓词,而不会出现问题。