我对此post进行了一些研究。但它的解决方案都不适合我。让我解释一下我做了什么:
实际上与上述帖子非常相似。
Category.h
@class Category, Item;
@interface Category : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSOrderedSet *items;
@property (nonatomic, retain) Category *parentcategory;
@property (nonatomic, retain) NSSet *subcategories;
@end
@interface Category (CoreDataGeneratedAccessors)
- (void)insertObject:(Item *)value inItemsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromItemsAtIndex:(NSUInteger)idx;
- (void)insertItems:(NSArray *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeItemsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInItemsAtIndex:(NSUInteger)idx withObject:(Item *)value;
- (void)replaceItemsAtIndexes:(NSIndexSet *)indexes withItems:(NSArray *)values;
- (void)addItemsObject:(Item *)value;
- (void)removeItemsObject:(Item *)value;
- (void)addItems:(NSOrderedSet *)values;
- (void)removeItems:(NSOrderedSet *)values;
- (void)addSubcategoriesObject:(Category *)value;
- (void)removeSubcategoriesObject:(Category *)value;
- (void)addSubcategories:(NSSet *)values;
- (void)removeSubcategories:(NSSet *)values;
@end
在我的视图控制器中,我加载了以下类别之一:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:kEntityCategory];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor
sortDescriptorWithKey:kAttributeCategoryName ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
NSError *error = nil;
AppDelegate* appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSArray* data = [appDelegate.dataCenter.document.managedObjectContext executeFetchRequest:request error:&error];
if ( data.count > 0)
{
self.category = [data objectAtIndex:0];
}
我在导航栏中有一个按钮用于测试目的。当它被点击时,我将复制第一个项目并添加到最后。
Item* item = [self.category.items objectAtIndex:0];
[self.category willChangeValueForKey:@"items"];
NSMutableOrderedSet *tempSet = [NSMutableOrderedSet orderedSetWithOrderedSet:self.category.items];
[tempSet addObject: item];
self.category.items = tempSet;
[self.category didChangeValueForKey:@"items"];
问题是项目根本没有添加到数据库中。 (我做了一些测试,例如,我修改了项目内容。它证明数据库完全没有问题。)但我不知道该项目不是数据库的原因。有人可以帮忙吗?感谢
答案 0 :(得分:20)
夫特:
let mutableItems = items.mutableCopy() as! NSMutableOrderedSet
mutableItems.addObject(anItem)
items = mutableItems.copy() as! NSOrderedSet
目标-C:
NSMutableOrderedSet *mutableItems = (NSMutableOrderedSet *)items.mutableCopy;
[mutableItems addObject:anItem];
items = (NSOrderedSet *)mutableItems.copy;
答案 1 :(得分:3)
问题解决了。有两个问题:
感谢。
答案 2 :(得分:1)
另一种方法是使用NSKeyValueCoding中的mutableOrderedSetValueForKey
函数。你可以说
owningObject.mutableOrderedSetValueForKey("items").addObject(anItem)
不幸的是,这并没有让你对"项目进行编译时检查。"
答案 3 :(得分:0)
let mutableItems = items.mutableCopy() as! NSMutableOrderedSet
mutableItems.add(anItem)
items = mutableItems.copy() as! NSOrderedSet