CoreData踩坑一则

我有如下一个Entity.

#import 
#import 

@class SubItem;
@interface Item : NSManagedObject 
{
  @private
}
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSOrderedSet *subitems;
@end

@interface Item (CoreDataGeneratedAccessors)
- (void)insertObject:(SubItem *)value inSubitemsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromSubitemsAtIndex:(NSUInteger)idx;
- (void)insertSubitems:(NSArray *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeSubitemsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInSubitemsAtIndex:(NSUInteger)idx withObject:(SubItem *)value;
- (void)replaceSubitemsAtIndexes:(NSIndexSet *)indexes withSubitems:(NSArray *)values;- (void)addSubitemsObject:(SubItem *)value;
- (void)removeSubitemsObject:(SubItem *)value;
- (void)addSubitems:(NSOrderedSet *)values;
- (void)removeSubitems:(NSOrderedSet *)values;
@end
#import "Item.h"
#import "SubItem.h"

@implementation Item
@dynamic name;
@dynamic subitems;
@end

可以看出我这个Item是能够调用方法- (void)addSubitems:(NSOrderedSet *)values;的。
然而当我如下操作时,却发生了错误。

Item *item = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:self.managedObjectContext];
item.name = @"FirstItem";
SubItem *subItem = [NSEntityDescription insertNewObjectForEntityForName:@"SubItem" inManagedObjectContext:self.managedObjectContext];
[item addSubitemsObject:subItem];

错误信息如下:

 *** -[NSSet intersectsSet:]: set argument is not an NSSet

我翻阅资料之后得知,这是apple自动生成代码的bug。
如何修复这个bug呢?
这里有一个比较讨巧的办法:重写- (void)addSubitems:(NSOrderedSet *)values;这个方法。

- (void)addSubitemsObject:(SubItem *)value {
  NSMutableOrderedSet* tempSet = [NSMutableOrderedSet orderedSetWithOrderedSet:self.subitems];
  [tempSet addObject:value];
  self.subitems = tempSet;
}

这样就巧妙的绕过了自动生成的代码。

你可能感兴趣的:(CoreData踩坑一则)