核心数据:保存唯一的对象ID
我看到有一种方法可以获取托管对象的唯一 ID:
NSManagedObjectID *moID = [managedObject objectID];
但是,正如我所读到的,它在保存时会发生变化。
有什么更好的方法来创建我自己的唯一 ID 并将其保存在每个对象中,确保它是唯一的并且不会更改?
I see that there is a method of getting the unique id of a managed object:
NSManagedObjectID *moID = [managedObject objectID];
But, as I have read, that changes when it is saved.
What is a better way of creating my own unique ID and saving it in each object, making sure that it IS unique and does't change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您无法将 NSManagedObjectID 保存在 CoreData 实体中,并且其中没有可用作整数或字符串 ID 的属性。
因此,构建您自己的唯一标识符算法是一个可接受的解决方案,如果您无法跟踪保存实体的时间,我对某些应用程序这样做了。
例如,我不久前遇到了类似的问题,当时我需要用对实体的引用填充 UITableView 单元格,并在单击/触摸单元格后检索实体。
我通过使用 uri 表示找到了一个建议,但是但是我仍然需要之前保存上下文,但我设法使用 NSFetchedResultsController 并找到了一个更可靠的解决方案,而不是应用程序构建的 id。
然后您可以稍后检索托管对象 id 本身:
并且使用 moid 我可以检索您的托管对象。
You cannot save the NSManagedObjectID in a CoreData entity, and there's no properties in it that can be intended as integer or string ID.
Therefore building your own unique identifier algorithm is an acceptable solution, if it's impossible for you to keep track when the entity is saved, I did this for some applications.
For example I had a similiar problem time ago, when I needed to fill a UITableView cells with a reference to the entity, and retrieve the entity after clicking/touching the cell.
I found a suggestion by using the uri representation, but however I still needed to save the context before, but I manage to use the NSFetchedResultsController and found a more solid solution rather than an application built id.
Then you can later retrieve the managed object id itself:
And with the moid I could retrieve your managed object.
我的对象中有一个创建的日期属性,所以我最终使用了该日期(包括秒),在我看来,它将是唯一的并且可以按照我想要的方式工作。
I have a created date property in my object, so I just ended up using that date including seconds, which, seems to me like it will be unique and work how I want.
您可以为对象创建一个 id 字段,并在
init
期间使用GUID
填充它。有关如何创建GUID
并可选择将其导出为字符串,请参阅 Cocoa 中的 UUID (GUID) 支持You can create an id field for your object, and populate it during
init
usingGUID
. for how to create aGUID
and optionally export it to string see UUID (GUID) Support in Cocoa如果它可以帮助其他人搜索这个,我就是这样做的:
在对象上创建一个 ID 属性
使用以下代码创建对象时获取最后使用的 ID:
在新对象上将其增加 1。
If it helps anyone else searching for this, this is how I do it:
Create an ID property on the object
Get the last used ID when creating an object with this code:
Increment this by one on the new object.