这是如何创建 NSManagedObject 的
NSEntityDescription *entity = [NSEntityDescription entityForName:strEntityName inManagedObjectContext:managedObjContext];
NSManagedObject * managedObject = (NSManagedObject *)[[NSClassFromString(strEntityName) alloc] initWithEntity:entity insertIntoManagedObjectContext:managedObjContext];
//values are mapped into this object
现在将 NSManagedObject 保存到持久存储并获取当前插入的对象,如下所示:
NSError *error;
BOOL isDone = [managedObjectContext save:&error];
//BOOL isDone = [managedObjectContext obtainPermanentIDsForObjects:[NSArray arrayWithObjects:tempManagedObject, nil] error:&error];
if (isDone && error == nil){
//fetch last inserted object here
//make fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:strEntityName];
//make query using fetch request in context
NSError *error;
NSArray *arrFetchRequest = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (arrFetchRequest.count>0){
//This is last inserted object
NSManagedObject *managedObject = [arrFetchRequest lastObject];
return managedObject;
}
}
我也提到了Swift - How to get last insert id in Core Data, store it in NSUserDefault and predicate。但它不会在NSManagedObject中拥有永久对象ID,因为我们正在保存临时ID并使用它来获取,而我们根本没有永久ID。
Canyone还有其他选择吗?
答案 0 :(得分:0)
在上下文中插入NSManagedObject时,它将具有temporaryID(这意味着它尚未保存到数据库中)。
因此需要在上下文中为NSManagedObject获取permanentID(这意味着它已保存到数据库),使用obtainPermanentIDsForObjects
并且相同的NSManagedObject将具有permanentID
if (insertManagedObject)
{
NSLog(@"Before %@ : %d",insertManagedObject.objectID,insertManagedObject.objectID.isTemporaryID);
//Obtain permanentID for object
NSError *error;
BOOL hasObtainedPermanentID = [managedObjectContext obtainPermanentIDsForObjects:[NSArray arrayWithObjects:insertManagedObject, nil] error:&error]; //;
//check if its done
if (hasObtainedPermanentID && error == nil){
NSLog(@"After %@ : %d",insertManagedObject.objectID,insertManagedObject.objectID.isTemporaryID);
//check context has changes and is saved in context
if ([managedObjectContext hasChanges] && [managedObjectContext save:&error])
{
return insertManagedObject;
}
}
}