Delete an object from one-to-many relationship

谁都会走 提交于 2019-12-13 00:57:10

问题


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) UserObjects 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!