所以我正在阅读Apple的核心数据指南和Stack上的问题,这一切都是正确的,但它并没有完全“点击”我的脑袋。
我有一个BookShop,它有一对多的书籍关系。
我进入了一家名为“Jenny's BookShop”的BookShop和一家名为“BigWorld Books”的书店。
这就是我将“新书”添加到“新书店”的方式:
BookShop *myBookShop = [NSEntityDescription insertNewObjectForEntityForName:@"BookShop" inManagedObjectContext:context]; myBookShop.books = [[NSMutableSet alloc]init]; Book *myBook = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:context]; myBook.BookShop = myBookShop;
[myBookShop addBookObject:myBook];
说我想要一本书只属于“BigWorld Books”而不是“Jenny's BookShop”。
我假设我使用获取请求并获取指向“BigWorld Books”的指针,然后将书分配给这个特定的书店?这就是我不断搞砸的地方。
如果有人能够“慢慢地”解释这一点,那将非常感激。
修改
答案:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@"]; [request setPredicate:predicate]; [request setFetchLimit:1]; BookShop *resultBookShop = [[_managedObjectContext executeFetchRequest:request error:&error] lastObject]; [myBook setBookShop:resultBookShop];
答案 0 :(得分:0)
//if BookShop with name BigWorld Books not existed, create. If existed, use it
BookShop *bookshop = [self isExistedEntityWitName:@"BigWorld Books" entity:@"BookShop"];
if(!bookshop){
//insertNewObjectForEntityForName
}else{
//bookshop is existed
//insert new book
Book *b = [NSEntityDescription insertNewObjectForEntityForName:@"Book"
inManagedObjectContext:context];
//add new book (b) to NSSet of bookshop, and you have NSSet *books
bookshop.books = books;
}