核心数据 - 数据库中行的主键ID [英] core data - the primary key id of a row in the database

查看:173
本文介绍了核心数据 - 数据库中行的主键ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个存储在Core Data中的书籍列表。我想通过它的主键ID搜索一本书。我知道Core Data创建的sqlite文件在每个表中都有一个ID列,但是这似乎并没有暴露给我。



解决方案

- [NSManagedObject objectID] 是Core Data中对象实例的唯一ID。它可以通过 - [NSManagedObjectID URIRepresentation] 序列化。您可以从具有 - [NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] 的持久存储协调器检索 objectID ,然后从管理对象上下文 - [NSManagedObjectContext objectWithID:]





您应该记住核心数据不是一个ORM。这是一个对象图管理框架。这就是使用SQLite(和唯一的行ID)作为后端纯粹是一个实现细节。越早你可以摆脱SQL / RDBMS心态,你将越快与核心数据。而不是试图从存储的ID找到一个对象,考虑为什么你需要该对象和什么对象需要它。如果 Foo 类的实例需要能够访问 Bar 类的实例,为什么不创建从 Foo Bar 关联,并设置适当的 Bar instance作为在适当的 Foo 实例上的关联的目标。让Core Data跟踪对象ID。


Suppose I have a list of books stored in Core Data. I want to search for a book by it's primary key ID. I know the sqlite file created by Core Data has an ID column in each table, but this doesn't seem to be exposed to me in anyway.

Does anyone have any recommendations?

Thanks!

解决方案

-[NSManagedObject objectID] is the unique ID for an object instance in Core Data. It can be serialized via -[NSManagedObjectID URIRepresentation]. You can retrieve the objectID from a persistent store coordinator with -[NSPersistentStoreCoordinator managedObjectIDForURIRepresentation:] and then get the object from a managed object context with -[NSManagedObjectContext objectWithID:].

BUT

You should keep in mind that Core Data is not an ORM. It is an object graph management framework. That is uses SQLite (and unique row IDs) as a backend is purely an implementation detail. The sooner you can get yourself out of the SQL/RDBMS mindset, the faster you will be happy with Core Data. Instead of trying to find an object from a stored ID, consider why you need that object and what object needs it. If an instance of class Foo needs to be able to get to an instance of class Bar, why not just create an association from the Foo to the Bar and set the appropriate Bar instance as the target of the association on the appropriate Foo instance. Let Core Data keep track of object IDs.

这篇关于核心数据 - 数据库中行的主键ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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