我对这篇文章做了一些研究。但它的解决方案都不适合我。让我解释一下我做了什么:
它实际上与提到的帖子非常相似。
类别.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"];
问题是该项目根本没有添加到数据库中。(我做了一些测试,比如我修改了item的内容,证明数据库完全没有问题。)但是我不知道item没有到数据库的原因。有人可以帮忙吗?谢谢