gpt4 book ai didi

ios - 从一对多关系中删除一个对象

转载 作者:行者123 更新时间:2023-11-29 13:02:11 24 4
gpt4 key购买 nike

两个实体:

  • 通知
  • 用户

User 有一个属性叫做 username

User <<---> Notification 之间存在一对多的关系,称为“用户”

保存了一个 Notification 对象 (ObjectA),该对象具有 (2) 个保存在“用户”关系中的 User 对象。我想通过删除“用户”关系中的 User 对象之一来更新 ObjectA。

User 实体有一个名为“username”的属性。

“用户”关系中有 (2) 个用户,用户名“UserA”和“UserB”作为对象,我该如何删除“UserA”?

这是我想出的方法,但它不起作用:

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

}];

编辑

enter image description here

从关系中删除“UserA”对象的最佳方法是什么?

最佳答案

如果删除“用户”对象也会删除相关的“通知”对象,那么您可能已经为从“用户”到“通知”再到“级联”的关系设置了“删除规则”。您应该将其设置为“Nullify”。

还要注意字符串比较

if (user.username == @"UserA")

错了,应该是

if ([user.username isEqualToString:@"UserA")

但这并不能解释为什么删除“通知”对象。

关于ios - 从一对多关系中删除一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com