在核心数据中,如果您在一个方向上设置关系,是否还需要设置反向关系还是自动设置?
我在两个方向都有一对多的关系。我在下面的第一个示例中设置它,但是要确保它在两个方向上设置。我怀疑它没有正确设置的原因是谓词在某些地方正常工作但在其他地方没有,所以如果这是错误的来源则要隔离。
//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;
答案 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关系都需要反向。