2010-01-15 116 views
3

我有我的数据模型中的用户和好友实体,是一个用户对许多朋友的关系。编辑核心数据关系数据

我的ViewController实例化为User(* user)的实例变量,因此我可以通过加载user.friends来访问所有朋友,因为朋友被定义为我的User对象中的NSSet。

在我的代码中,我加载一个NSMutableArray中的所有朋友,做一些事情,并可能在离开之前想要添加其他朋友,并编辑现有朋友的属性。我对如何添加/编辑朋友感到茫然。

我应该编辑朋友对象的NSMutableArray,并将其保存回User.context?如果是这样,怎么样?

如果编辑朋友,我应该复制现有的朋友对象,更改值,从数组中删除旧对象,并添加新的(复制和更新)?

我希望这是有道理的......

回答

1

您可以修改您的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 
} 
+0

谢谢 - 这种方法似乎正在工作。 – mootymoots 2010-01-15 12:38:25

0

如果你有一个指针/引用到NSManagedObject您可以编辑的所有属性。假设你得到一个朋友是这样的:

Friend *aFriend = [user.friends anyObject]; 
[aFriend setLastName:@"new Lastname"]; 
NSError *error = nil; 
[[self managedObjectContext] save:&error]; 

要添加好友做这个:

Friend *aNewFriend = [NSEntityDescription insertNewObjectForEntityForName:@"friend" inManagedObjectContext:[self managedObjectContext]]; 
[user addFriendsObject:aNewFriend]; 
NSError *error = nil; 
[[self managedObjectContext] save:&error]; 

然而,这将不是新的朋友添加到您从先前设置的user.friends创建的NSMutableArray 。

+0

嗨, 我没有NSManagedObject在我的控制器(我不你认为?)。我设置我的视图控制器从一个UITableView像这样: User * user =(User *)[fetchedResultsController objectAtIndexPath:indexPath]; viewController.user = user; 并在该视图控制器,我得到这样的朋友: NSMutableArray * friends = [[NSMutableArray alloc] initWithArray:[user.friends allObjects]]; 这是错误的方法 - 我已经在Core Data中复制了iPhone食谱的Apple示例代码。 – mootymoots 2010-01-15 11:13:49

+0

我应该补充的是,用我的方法我可以得到user.context,那么我可以保存吗? – mootymoots 2010-01-15 11:19:23

+0

使用NSFetchedResultsController时,您可以完全跟踪更改。任何更改都会报告给您的控制器,您可以将其保存在上下文中。查看文档中的概述了解更多信息 - http://developer.apple.com/iphone/library/documentation/CoreData/Reference/NSFetchedResultsController_Class/Reference/Reference.html – Anurag 2010-01-15 11:36:27