我在上面尝试了Tony Arnold 的回答来解决类似的问题,但是在一次删除多个“容器”时发现了问题(这是在 OS X 10.8.2 上)。[item itemContainers]
在保存托管对象上下文之前不会删除容器,因此count
保持在 1 以上并且item
永远不会被删除。
我想出了以下解决方案-[NSManagedObject isDeleted]
,在NSManagedObject
.
文件NSManagedObject+RJSNondeletedObjects.h
#import <CoreData/CoreData.h>
@interface NSManagedObject (RJSNondeletedObjects)
- (NSSet *)RJS_nondeletedObjectsForToManyKeyPath:(NSString *)keyPath;
- (BOOL)RJS_hasOtherNondeletedObjectsForToManyKeyPath:(NSString *)keyPath;
@end
文件NSManagedObject+RJSNondeletedObjects.m
#import "NSManagedObject+RJSNondeletedObjects.h"
@implementation NSManagedObject (RJSNondeletedObjects)
- (NSSet *)RJS_nondeletedObjectsForToManyKeyPath:(NSString *)keyPath
{
NSSet * result = nil;
id allObjectsForKeyPath = [self valueForKeyPath:keyPath];
if ( ![allObjectsForKeyPath isKindOfClass:[NSSet class]] ) return result;
result = [(NSSet *)allObjectsForKeyPath objectsPassingTest:^BOOL(id obj, BOOL *stop)
{
BOOL testResult = ![obj isDeleted];
return testResult;
}];
return result;
}
- (BOOL)RJS_hasOtherNondeletedObjectsForToManyKeyPath:(NSString *)keyPath
{
BOOL result = NO;
// self will be in the set of nondeleted objects, assuming it's not deleted. So we need to adjust the test threshold accordingly.
NSUInteger threshold = [self isDeleted] ? 0 : 1;
NSSet * nondeletedObjects = [self RJS_nondeletedObjectsForToManyKeyPath:keyPath];
result = ( [nondeletedObjects count] > threshold );
return result;
}
@end
Container
班级
...
#import "NSManagedObject+RJSNondeletedObjects.h"
...
- (void)prepareForDeletion
{
NSSet *childItems = [self items];
for (Item *item in childItems) {
if ([item RJS_hasOtherNondeletedObjectsForToManyKeyPath:@"containers"]) {
continue;
}
[managedObjectContext deleteObject:item];
}
}