我试图通过一组标记对象进行枚举,每个对象都有一个对应的核心数据实体,该实体具有“tag”属性,我将其用作谓词来获取枚举对象的正确实体。见下面的代码。
这似乎导致了一些问题,因为我正在更新枚举中的实体,我怀疑问题是fetch比枚举慢。我如何通过此数组枚举并正确更新获取实体?
[array enumerateObjectsUsingBlock:^(obj *SomeClass, NSUInteger idx, BOOL *stop){
currentEntityForEnumeratedObject = [targetVC fetchEntityForTag:obj.tag createIfNeccessary:NO error:nil];
currentEntityForEnumeratedObject.someAttribute = [NSNumber numberWithInt:obj.somePropertyOfObj];
}];
答案 0 :(得分:1)
原则上,您无法更新要枚举的对象。来自documentation:
即使集合是可变的,也不能在快速枚举期间改变集合。如果您尝试在循环中添加或删除收集的对象,则会生成运行时异常。
另外,在我看来,在枚举循环中进行提取是次优设计。相反,您应该获取所有对象,然后迭代它们以修改它们。您可以使用特殊谓词语法来获取集合中具有特定属性的所有记录:
// make a collection of all the tags of the *SomeClass objects
NSArray *tags = [array objectForKeyPath:@"tag"];
// fetch all relevant records with this predicate
[NSPredicate predicateWithFormat:@"tag in %@", tags];