Editing Relational Master Data

I have User and Friend objects in my data model that are one user for many relationships with friends.

My ViewController, an instance of the variable is created for the user (* user), and therefore I can access all friends by loading user.friends as friends as an NSS object in my User object.

In my code, I load all friends into NSMutableArray, do some things, and maybe before leaving I want to add additional friends and edit the attributes of existing friends. I do not understand how I can add / edit friends.

Should I edit NSMutableArray objects for friends and save them back to User.context? If so, how?

If you are editing a friend, should I copy an existing friend object, change the values, delete the old object from the array and add a new (copied and updated) one?

Hope this makes sense ...

+3
source share
2 answers

You can change Friend objects (no need to create new copies and delete old ones).

Try the following:

// create a mutable copy of an array from the set of the user 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 new friends
user.friends = [NSSet setWithArray:friends];
[friends release];

// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
    // handle error
}

You can also use a mutable set instead of an array:

// create a mutable copy of the set of the user 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 new friends
user.friends = [NSSet setWithSet:friends];
[friends release];

// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
    // handle error
}
+1
source

If you have a pointer / link to NSManagedObject, you can edit all the attributes. Say you have a friend like this:

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

To add a friend, follow these steps:

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

However, this will not add a new friend to the NSMutableArray that you created from previously created user.friends.

0

Source: https://habr.com/ru/post/1728597/


All Articles