5

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

示例代码:

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];
4

3 回答 3

5

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

如果您给出的代码被频繁调用,并且您希望加快速度,这里有一些想法可以尝试:

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

如果您愿意,我可以编写一些示例代码。

于 2012-05-20T19:06:28.323 回答
1

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

NSPredicate *predicates = [NSCompoundPredicate andPredicateWithSubpredicates:NSArray_of_predicates];
于 2012-05-20T15:17:27.660 回答
1

It's OK if you reuse them with the same store, or perhaps different stores with the same model. I ran into crashes (e.g. in NSKnownKeysDictionary1) when using the same fetch request to query multiple stores that had different models. It seemed to make sense to reuse the request since I was fetching the same entity, just from two different places. The entity name and predicate were the same. You would think this would be OK since the fetch request takes an entity name rather than an entity description; the latter would be a different (but equivalent) object for the same entity in different stores/models. However, it looks like the fetch request caches the entity description and doesn't check that it's still valid for the current context that it's being executed against.

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

于 2019-01-11T22:24:11.320 回答