首页 > 解决方案 > Auto-generated Core Data accessor returns deleted objects

问题描述

I have two simple Core Data models: Patient and Treatment. There is a one-to-many relationship from Patient to Treatment, so a Patient can have multiple Treatments, but each Treatment always has one Patient.

There is an auto-generated accessor property of Patient called treatments, defined in Patient+CoreDataProperties.h:

@property (nullable, nonatomic, retain) NSSet<Treatment *> *treatments;

I have a patient view that lists all his/her treatments. The user can swipe delete treatments from the list.

When I delete a treatment that is related to a patient (they all are) like this:

[managedObjectContext deleteObject:treatment];
/* I even tried this: */
NSMutableSet *treatments = [patient mutableSetValueForKey:@"treatments"];
if ([treatments containsObject:treatment]) {
  /* this actually is the case */
  [treatments removeObject:treatment];
  patient.treatments = treatments;
}

[managedObjectContext save];

the patient.treatments property still contains the deleted treatment. I also tried to delay the table reload using dispatch_async - did not help.

The deleted treatment is in a faulted state; does this mean I'm required to kick out faulty objects from the treatments NSSet by hand? What can I do to force Core Data to update the treatments NSSet?

If I terminate the app and restart, the deleted treatment is gone.

标签: ioscore-data

解决方案


回答我自己的问题...

经过半夜的尝试和错误,我发现调用

[moc refreshObject:patient],

作为对更改通知的响应,导致删除的处理一直存在,直到应用重新启动。删除治疗也触发了通知,所以也许有某种……副作用。


推荐阅读