Core Data/NSOperation: crash while enumerating through and deleting objects

前端 未结 1 371
生来不讨喜
生来不讨喜 2021-01-05 05:12

I have a core data based app that has a one object (a list) to many objects (list items) relationship. I\'m working on syncing data between devices, and as part of that I im

1条回答
  •  隐瞒了意图╮
    2021-01-05 05:30

    There is a bit of a clue in the error message, where you can see the class NSFaultingMutableSet listed. Indeed the set you are enumerating is really just a proxy for the to-many relationship that will potentially load data on demand. Since items in the collection are being marked as deleted during the enumeration, the possibility exists that some of the collection will 'change' while you're enumerating it and you'll see that error.

    A common way to deal with this is to create a copy of the collection and enumerate the copy. The naive approach to that would just be:

    NSSet *iterItems = [[list.items copy] autorelease];
    for (ListItemCD *item in iterItems) { ... }
    

    But I've found when dealing with Core Data that -copy does not actually return a copy but often just another faulting proxy. So I instead choose to copy the collection this way:

    NSSet *iterItems = [NSSet setWithSet:list.items];
    for (ListItemCD *item in iterItems) { ... }
    

    0 讨论(0)
提交回复
热议问题