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

时间:2017-08-12 18:11:25

标签: ios objective-c core-data one-to-many

在核心数据中,如果您在一个方向上设置关系,是否还需要设置反向关系还是自动设置?

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

//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;

1 个答案:

答案 0 :(得分:2)

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

您选择的命名有点令人困惑。我们通常使用复数名词来表达多对多的关系。而且我不确定如果将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关系都需要反向。