问题
Two Entities:
Notification
User
User
has an attribute called username
There is one-to-many relationship
between User
<<---> Notification
called "users"
There is a Notification
object (ObjectA) saved that has (2) User
Objects saved in the "users" relationship. I would like to update ObjectA by deleting one of the User
object in "users" relationship.
User
entity has an attribute called "username".
There are (2) User'
s with username "UserA" & "UserB" as objects in the "users" relationship, how would I delete "UserA"?
Here is what I came up with and it's not working:
NSFetchRequest *notificationRequest = [[NSFetchRequest alloc] initWithEntityName:@"Notification"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"notification_id == %@", [selectedManagedObject valueForKey:@"notification_id"]];
[self.managedObjectContext executeFetchRequest:notificationRequest onSuccess:^(NSArray *results)
{
//Since I'm fetching based on objectID, there should always be one Object.
Notification *notificationObject = [results objectAtIndex:0];
NSArray *usersArray = [NSArray alloc]init];
//I don't think the code below is correct?
usersArray = [notificationObject valueForKey:@"users"];
for (User *user in userArray)
{
if (user.username == @"UserA")
{
[self.managedObjectContext deleteObject:user];
[self.managedObjectContext saveOnSuccess:^{
} onFailure:^(NSError *error) {
}];
} onFailure:^(NSError *error) {
}];
EDIT

What's the best way to delete "UserA" object from the relationship?
回答1:
If deleting a "User" object also deletes the related "Notification" object, then you probably have set the "Delete Rule" for the relationship from "User" to "Notification" to "Cascade". You should set it to "Nullify" instead.
Note also that the string comparison
if (user.username == @"UserA")
is wrong, it should be
if ([user.username isEqualToString:@"UserA")
That does however not explain why the "Notification" object is deleted.
来源:https://stackoverflow.com/questions/19508538/delete-an-object-from-one-to-many-relationship