我的模型中有一个NSManagedObject
属性childNodes
。现在我想覆盖childNodes
属性并返回它的过滤版本,但我一直在崩溃。这是我在NSMO
子类中的内容:
- (NSOrderedSet *)childNodes {
[self willAccessValueForKey:@“childNodes”];
NSMutableOrderedSet *result = [self primitiveChildNodes];
[self didAccessValueForKey:@"childNodes”];
NSArray *filteredResult = [[result array] myCustomArrayFilteringMethod]; // let’s say this returns the first half of the array, as a contrived example
return [NSOrderedSet orderedSetWithArray:filteredResults];
}
这有时候工作正常,但我发现像Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSOrderedSet objectsAtIndexes:]: index 24 in index set beyond bounds [0 .. 19]’
这样的崩溃,我不知道为什么。调用堆栈似乎与变异集合有关,但我正在改变副本,所以我不确定发生了什么:
0 CoreFoundation __exceptionPreprocess + 165
1 libobjc.A.dylib objc_exception_throw + 48
2 CoreFoundation -[NSOrderedSet objectsAtIndexes:] + 952
3 Foundation NSKeyValueWillChangeByOrderedToManyMutation + 568
4 Foundation NSKeyValueWillChange + 383
5 Foundation -[NSObject(NSKeyValueObserverNotification) willChange:valuesAtIndexes:forKey:] + 557
6 CoreData -[NSManagedObject(_NSInternalMethods) _excludeObject:fromPropertyWithKey:andIndex:] + 526
7 CoreData -[NSManagedObject(_NSInternalMethods) _maintainInverseRelationship:forProperty:oldDestination:newDestination:] + 254
8 CoreData -[NSManagedObject(_NSInternalMethods) _didChangeValue:forRelationship:named:withInverse:] + 567
9 Foundation NSKeyValueNotifyObserver + 347
10 Foundation NSKeyValueDidChange + 466
11 Foundation -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:] + 118
12 CoreData -[NSManagedObject didChangeValueForKey:] + 135
13 CoreData -[NSManagedObject(_NSInternalMethods) _updateFromRefreshSnapshot:includingTransients:] + 758
14 CoreData -[NSManagedObjectContext(_NestedContextSupport) _copyChildObject:toParentObject:fromChildContext:] + 567
15 CoreData -[NSManagedObjectContext(_NestedContextSupport) _parentProcessSaveRequest:inContext:error:] + 1103
16 CoreData __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 364
17 CoreData internalBlockToNSManagedObjectContextPerform + 84
18 libdispatch.dylib _dispatch_client_callout + 8
19 libdispatch.dylib _dispatch_barrier_sync_f_slow_invoke + 284
20 libdispatch.dylib _dispatch_client_callout + 8
21 libdispatch.dylib _dispatch_main_queue_callback_4CF + 1738
22 CoreFoundation __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
23 CoreFoundation __CFRunLoopRun + 2073
24 CoreFoundation CFRunLoopRunSpecific + 488
25 GraphicsServices GSEventRunModal + 161
26 UIKit UIApplicationMain + 171
27 My app main + 111
28 libdyld.dylib
有什么建议吗?我不太清楚这一点。
答案 0 :(得分:0)
不要。添加一个不同的方法,返回原始关系的过滤副本。此外,为了实现,只需迭代集合并将要保留的项目添加到一个全新的集合中,不要复制和过滤。
崩溃是因为您过滤的数组实际上是由数据存储区支持的,因此当您对其进行过滤时,它会更改您使用过滤器进行迭代的内容,并且搞砸了原来的关系。