【问题标题】:core data fetch entity during enumeration of array枚举数组期间的核心数据获取实体
【发布时间】:2013-09-22 03:52:33
【问题描述】:

我试图通过一个标记对象数组进行枚举,每个对象都有一个相应的核心数据实体,该实体具有一个“标记”属性,我将其用作谓词来获取枚举对象的正确实体。请参阅下面的代码。

这似乎导致了一些问题,因为我正在更新枚举中的实体,并且我怀疑问题是获取比枚举慢。如何枚举这个数组并正确更新获取实体?

[array enumerateObjectsUsingBlock:^(obj *SomeClass, NSUInteger idx, BOOL *stop){

    currentEntityForEnumeratedObject = [targetVC fetchEntityForTag:obj.tag createIfNeccessary:NO error:nil];

    currentEntityForEnumeratedObject.someAttribute = [NSNumber numberWithInt:obj.somePropertyOfObj];

}];

【问题讨论】:

  • 首先:如果 currentEntityForEnumeratedObject 未获取您返回 nil 会发生什么?二:enumerateObjectsUsingBlock 是同步执行,它在你调用后端的 fetchEntityForTag 中?

标签: ios objective-c xcode core-data nsarray


【解决方案1】:

原则上,您不能更新您正在枚举的对象。来自documentation

即使集合是可变的,您也不能在快速枚举期间改变集合。如果您尝试在循环中添加或删除收集的对象,您将生成运行时异常。

另外,在我看来,在枚举循环中进行 fetch 是次优设计。相反,您应该获取所有对象,然后遍历它们以修改它们。您可以使用特殊的谓词语法来获取集合中具有特定属性的所有记录:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多