假设我在公司实体中有员工关系,并且是一对多关系。而且数量确实很多。苹果公司 100 年来,拥有 1,258,500,073 名员工。
我可以简单地做一些事情
NSInteger numEmployees = [apple.employees count];
没有触发 1.258.500.073 故障? (好吧,100 年后,iPhone 将轻松处理如此多的物体,这是肯定的......但无论如何)
最佳答案
-count
不会引发错误。如果内存中已经有父对象,那么这是获取该计数的最佳方法。
如果内存中没有对象,那么性能更高的方法是:
NSManagedObjectContext *moc = ...;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"child" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"parent == %@", parent]];
NSError *error = nil;
NSInteger count = [moc countForFetchRequest:request error:&error];
NSAssert2(error == nil, @"Error fetching request: %@\n%@", [error localizedDescription], [error userInfo]);
[request release], request = nil;
它在数据库级别执行计数。
关于iphone - 检查核心数据中的一对多关系引用了多少对象的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031813/