我的数据模型中有用户和 friend 实体,是一对多 friend 的一对一关系。
我的 ViewController 是用 User (*user) 的实例变量实例化的,因此我可以通过加载 user.friends 来访问所有 friend ,因为 friend 在我的 User 对象中定义为 NSSet。
在我的代码中,我将所有 friend 加载到 NSMutableArray 中,做一些事情,并且可能在离开之前想要添加其他 friend ,并编辑现有 friend 的属性。我不知道如何添加/编辑 friend 。
我应该编辑好友对象的 NSMutableArray 并将其保存回 User.context 吗?如果是这样,怎么办?
如果编辑好友,我是否应该复制现有好友对象、更改值、从数组中删除旧对象并添加新的(复制和更新的)对象?
我希望这是有道理的......
最佳答案
您可以修改您的 Friend 对象(无需创建新副本并删除旧对象)。
试试这个:
// create a mutable copy of an array from the set of the user's friends
NSMutableArray *friends = [[user.friends allObjects] mutableCopy];
// modify friends array or any Friend objects in the array as desired
// create a new set from the array and store it as the user's new friends
user.friends = [NSSet setWithArray:friends];
[friends release];
// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
// handle error
}
您还可以使用可变集而不是数组:
// create a mutable copy of the set of the user's friends
NSMutableSet *friends = [user.friends mutableCopy];
// modify friends set or any Friend objects in the set as desired
// create a new set from the set and store it as the user's new friends
user.friends = [NSSet setWithSet:friends];
[friends release];
// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
// handle error
}
关于iphone - 编辑核心数据关系数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2070912/