保存后Core Data objectID为零

时间:2016-08-31 15:16:52

标签: ios objective-c xcode core-data

我有一个核心数据对象,我通过objectID.URIRepresentation访问它。将此对象保存到Core Data后,objectId为nil,如何从Core Data获取新更新的对象,此对象有一个唯一ID,但在生命周期的这一点上我不存在。

任何帮助都会非常感激,我已经尝试了几个小时。

由于

1 个答案:

答案 0 :(得分:1)

当新实体插入核心数据上下文时,它会收到临时标识符。保存上下文时,它将被永久ID替换。如果您需要在此之前获取对象ID,可以使用方法获取它:

- (BOOL)obtainPermanentIDsForObjects:(NSArray *)objects
                               error:(NSError **)error

此方法将对象中每个托管对象的对象ID转换为永久ID。虽然该对象将具有永久ID,但它仍将对isInserted作出积极响应,直到保存为止。任何已拥有永久ID的对象都将被忽略。

<强>更新

要获得永久ID,您需要执行以下操作:

// Say you have inserted new managed object you want to get permanent ID of. 
// If you check current objectID after that it will be temporary ID.
NSManagedObject *obj = [NSEntityDescription insertNewObjectForEntityForName:kSomeEntityName inManagedObjectContext:ctx];

// After you have inserted new managed object into the context 
// (or an array of objects) try to obtain permanent Ids.
if (![ctx obtainPermanentIDsForObjects:@[obj] error:&err]) {
    // The operation fails. Handle an error.
    NSLog(@"Could not obtain permanent ID for object %@, error %@ %@", obj, err, err.userInfo);
    abort();
}

// Now object ID of inserted object is permanent and it will not be
// changed during save operation. Store permanent ID for future use
NSManagedObjectID *objID = [obj objectID];