NSManagedObject中未保存的NSSet成员是否会在保存时保留已删除的成员?

时间:2014-02-14 17:18:10

标签: ios cocoa-touch core-data nsmanagedobject

我今天遇到了一位同事的有趣问题。答案起初看起来很简单,但后来我意识到我从未见过任何文件来支持我的假设。

如果NSManagedObject PersonFriends之间存在一对多的关系(例如friend1,以及下面的代码 - 那么friend2NSManagedObjectContext *context = [a private context]; Person *aPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:context]; NSMutableSet *friendsSet = [NSMutableSet new]; // Create some friends in the private context Person *aFriend1 = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:context]; [friendsSet addObject:friend1]; Person *aFriend2 = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:context]; [friendsSet addObject:friend2]; // Add these friends to aPerson [person addFriends:friendsSet]; // Alas! aPerson decides they want better friends. NSMutableSet *betterFriendsSet = [NSMutableSet new]; Person *aFriend3 = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:context]; [betterFriendsSet addObject:friend3]; Person *aFriend4 = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:context]; [betterFriendsSet addObject:friend4]; // Dump those old friends aPerson.friends = nil; // Add the new friends [person addFriends:betterFriendsSet]; // Save [context save:nil]; 被持久保存到数据存储区?

{{1}}

aPerson在数据存储中有2个朋友还是4个?我的假设是2,因为不再有对friend1和friend2的任何强引用,它们应该被释放。但是,核心数据生成的访问器可能在幕后做得更多并且对它们有强烈的引用,在这种情况下它们将被持久化到数据存储。

2 个答案:

答案 0 :(得分:1)

你实际上是在问两件事:

  

将friend1和friend2保存到数据存储中吗?

是。您将它们添加到托管对象上下文,然后保存更改。他们是否得到保存不受它们是否与aPerson相关的影响。这与生成的访问器没有任何关系,只是您将它们添加到上下文中并且从未删除它们。如果您不想保留它们,则需要删除它们。

  

aPerson在数据存储中有2个朋友还是4个?

它有两个。由于您将friends设置为nil,因此您删除了前两个好友实例的关系。当您的代码完成后,aPerson有两个朋友。之前的朋友仍然在持久性商店中,但他们不再与任何Person相关联。

答案 1 :(得分:0)

好吧,首先,提供的Core Data方法为Core Data属性添加和删除set成员是(示例属性是“Ratings”): 添加一个成员

- (void)addRatingsObject:(RatingsDB *)value;
- (void)removeRatingsObject:(RatingsDB *)value;

添加一组成员

- (void)addRatings:(NSSet *)value;
- (void)removeRatings:(NSSet *)value;

接下来,insertNewObjectForEntityForName方法将为“Friend”创建Core Data对象,无论您使用NSSet内容做什么,它们都会保存。它们将与使用nil创建的“Person”实体取消链接。

完成后,您将有四个“朋友”记录。