用一个或两个语句设置关系和逆

Set relationship and inverse with one statement or two

在core data中,如果设置了单向关系,是否还需要设置反向关系,还是自动设置?

我在两个方向上都有一对多的关系。我将其设置为下面的第一个示例,但要确保它是在两个方向上设置的。我怀疑它没有正确设置的原因是谓词在某些地方可以正常工作,但在其他地方则不能,所以如果这是错误的来源,我想隔离。

//code to select book from existing books

//Create relationship with author
IS this sufficient?

NSSet*existingBookInSet = [NSSet setWithObjects:bookForAuthor, nil];
_author.book = existingBookInSet;

或者我需要做什么:

NSSet*existingBookInSet = [NSSet setWithObjects:bookForAuthor, nil];
_author.book = existingBookInSet;
NSSet*authorSet = [NSSet setWithObjects:_author, nil];
bookForAuthor.author = authorSet;

确保将关系定义为彼此相反的关系。然后设置一个关系会自动设置另一个。

您选择的命名有点混乱。对于一对多关系,我们通常使用复数名词。而且我不确定如果将 NSSet 传递给 setter 而不是 NSMutableSet 会发生什么。我宁愿看到像

这样的东西
book1.author = author;
book2.author = author;
NSLog(@"%@", author.books);
... prints the set of two books 

或者,如果您更愿意从另一个方向努力:

NSMutableSet *authorBooks = [NSMutableSet setWithObjects:book1, book2, nil];
author.books = authorBooks;
NSLog(@"%@", book1.author);
... prints the author

你不需要这两个,只要一个,只要模型正确定义逆。请注意,根据 Apple 文档,每个 Core Data 关系都需要一个逆关系。