如何获取保存到Core Data的受管对象上下文的对象的ID? [英] How to get the ID of an object saved to Core Data's managed object context?

查看:177
本文介绍了如何获取保存到Core Data的受管对象上下文的对象的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

NSEntityDescription *userEntity = [[[engine managedObjectModel] entitiesByName] objectForKey:@"User"];
User *user = [[User alloc] initWithEntity:userEntity insertIntoManagedObjectContext:[engine managedObjectContext]];

,我想知道插入到受管对象上下文的对象的id。

and I want to know the id of the object inserted to the managed object context. How can i get that?

该id对于该对象的生命周期是否保持不变,或者它会持续到该对象下面的sqlLite数据库,并且是可以用于唯一

Will that id remain the same for that object's lifetime or will it persist to the sqlLite database beneath this and be something that can be used to uniquely identify it during a fetch operation (my ultimate goal).

任何帮助//:)

推荐答案

如果要永久保存对象的ID,您需要:

If you want to save an object's ID permanently you need to:


  1. 将对象保存到上下文

  2. 使用 - [NSManagedObjectID URIRepresentation] 。

  3. 您可以使用 - [NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:]来获取对象生成一个新的 NSManagedObjectID 对象,然后使用 - [NSManagedObjectContext objectWithID:]

  1. Save the object into the context so that the ID changes from a temporary to a permanent ID.
  2. Extract the URI version of the permanent ID with -[NSManagedObjectID URIRepresentation]. That returns a NSURL you can store as transformable attribute in another managed object.
  3. You can get the object by using -[NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] to generate a new NSManagedObjectID object and then use -[NSManagedObjectContext objectWithID:] to get the actual referenced managed object.

URI应该标识特定计算机上特定商店中的特定对象,但如果您进行任何结构更改到商店,如将其迁移到新的模型版本。

The URI is supposed to identify a particular object in a particular store on a particular computer but it can change if you make any structural changes to the store such as migrating it to a new model version.

但是,您可能不需要执行任何操作。 ObjectID在核心数据中的作用要小于在其他数据模型系统中。 Core Data维护一个对象图,通过它们在图中的位置唯一地标识对象。简单地走图形关系,你可以看到一个特定的唯一对象。

However, you probably don't need to do any of this. ObjectIDs play a much smaller role in Core Data than they do in other Data Model systems. Core Data maintains an object graph that uniquely identifies objects by their location in the graph. Simply walking the graph relationships takes you to a specific unique object.

你真正需要ObjectID的唯一方法是当你在两个或多个持久化存储上访问对象时。你需要他们,因为关系不交叉商店。

The only time you really need ObjectID is when you're accessing object across two or more persistent stores. You need them then because relationships don't cross stores.

这篇关于如何获取保存到Core Data的受管对象上下文的对象的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆