Core Data保存上下文后,未删除的对象值为null

时间:2015-01-13 11:31:36

标签: objective-c core-data nspredicate nsmanagedobjectcontext nsfetchrequest

我有一个具有objectIdobjectName属性的对象。在使用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的值为null?

根据评论进行修改

theObject是在prepareForSegue方法中从父视图控制器设置的。

destinationViewController.theObject = self.theObjectsArray[indexPath.row];

我在theObject中记录了viewDidLoad值,并且设置成功。

1 个答案:

答案 0 :(得分:0)

简短的回答是:是的,这就是它的运作方式。

为了解释,我需要首先假设theObject是核心数据中的托管对象。因此它继承自NSManagedObjecctID,这使您能够通过objectId查询它。

您可以将Object视为指向托管对象上下文中托管对象的指针。 id是使该对象在给定上下文中100%唯一的原因。

因此,当您对该对象发出请求时,核心数据将返回给您,因为您使用其id请求了Object。

请参阅:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdFaultingUniquing.html

核心数据不会返回您请求的对象的某些副本(在这种情况下它将是一个不同的指针,但是相同的数据),它会返回您请求的特定实例。

相关问题