【发布时间】:2015-01-13 11:31:36
【问题描述】:
我有一个具有objectId 和objectName 属性的对象。在我使用 Core Data 的 deleteObject 函数删除一个项目并保存上下文后,即使我只将该对象用作谓词,该对象的值为 null。这是我的代码。
NSLog(@"%@", self.theObject.name); // it returns the object's name
NSError *error = nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"MyEntity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"objectId==%@", self.theObject.objectId];
fetchRequest.predicate = predicate;
NSArray *myObjects = [context executeFetchRequest:fetchRequest error:&error];
for (MyClass *myObject in myObjects) {
[context deleteObject:myObject];
}
if (![context save:&error]) {
NSLog(@"Could not delete! %@ %@", error, [error localizedDescription]);
} else {
NSLog(@"%@", self.theObject.name); // it returns null
}
这是 Core Data 的默认行为,还是我遗漏了什么?为什么theObject的值只用于谓词时为空?
根据评论编辑
theObject 是在 prepareForSegue 方法中从父视图控制器设置的。
destinationViewController.theObject = self.theObjectsArray[indexPath.row];
我在viewDidLoad 中记录了theObject 的值,并且设置成功。
【问题讨论】:
-
看起来您删除了上下文中具有 theObject ID 的对象...应该是 theObject ... ?!
-
@Volker 我只是使用了对象的 ID 作为谓词,并用请求填充了 myObjects 数组。我只删除了 myObject(即 MyClass),但保存上下文后 theObject 的值为 null。这太令人困惑了。附言myObject 和 theObject 是不同的类。
-
所以如果 theObject 显示为 null 肯定有某种原因,它不会神奇地发生。也许您会提供更多详细信息来创建对象。通过在谓词中使用它,它的值不会被重置为 NULL
-
最好将此信息作为编辑添加到您的问题中。还要添加您派生对象的方式。它是否也从您的上下文中加载?如果是,为什么不应该在执行上面显示的删除时将其删除?
-
@Volker 的最后一条评论是正确的,如果条件成立的话。那么,你的目标是什么?
标签: objective-c core-data nspredicate nsmanagedobjectcontext nsfetchrequest