Two Entities:
两个实体:
Notification
- 通知
User
- 用户
User
has an attribute called username
用户有一个名为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.
有一个通知对象(ObjectA)保存了在“用户”关系中保存的(2)用户对象。我想通过删除“用户”关系中的一个用户对象来更新ObjectA。
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"?
有(2)用户名“UserA”和“UserB”作为“用户”关系中的对象,我将如何删除“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?
从关系中删除“UserA”对象的最佳方式是什么?
1 个解决方案
#1
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.
如果删除一个“用户”对象也删除了相关的“通知”对象,那么您可能已经设置了“删除规则”从“用户”到“通知”到“级联”的关系。您应该将其设置为“Nullify”。
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.
但是,这并不能解释为什么会删除“通知”对象。
#1
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.
如果删除一个“用户”对象也删除了相关的“通知”对象,那么您可能已经设置了“删除规则”从“用户”到“通知”到“级联”的关系。您应该将其设置为“Nullify”。
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.
但是,这并不能解释为什么会删除“通知”对象。