NSManagedObjectID转换为NSData [英] NSManagedObjectID into NSData

查看:278
本文介绍了NSManagedObjectID转换为NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个美妙的NSManagedObjectID。这将非常有利于引用Entity / NSManagedObject / NSEntityDescription,对吗?

让我们从一个实体获取一个ID:

I found this wonderful NSManagedObjectID. This would be very good for referencing an Entity/NSManagedObject/NSEntityDescription, right?
Let's get an ID from an entity:

NSEntityDescription *entity = [self newEntity];     
NSManagedObjectID *objID = [entity objectID];

所以...任何想法如何得到 objID into一个字符串?或更好:NSData。实际上是能够将其保存到NSUserDefaults的东西。 ;-)

So... any idea how to get this objID into a string? Or better: NSData. Actually something to be able to save it to the NSUserDefaults. ;-)

Btw:NSFetchRequest不想在我的情况下工作。我使用此示例的修改版本:对一个旧问题的回答

Btw: NSFetchRequest doesn't want to work in my case. I use an modified version of this example: answer of an old question.

推荐答案

要获取与 NSManagedObject objectID

NSManagedObject* myMO;
...
NSURL *uri = [[myMO objectID] URIRepresentation];
NSData *uriData = [NSKeyedArchiver archivedDataWithRootObject:uri];

为了回到原始托管对象的实例,您需要一个CoreData堆栈持有该实例已经添加 NSPersistentStoreCoordinator 。然后:

In order to get back to an instance of the original managed object, you need a CoreData stack with the persistent store holding that instance already added to the NSPersistentStoreCoordinator. Then:

NSData *uriData;
NSPersistentStoreCoordinator *psc;
NSManagedObjectContext *moc; //with moc.persistentStoreCoordinator = psc.
...
NSURL *uri = [NSKeyedUnarchiver unarchiveObjectWithData:uriData];
NSManagedObjectID *moID = [psc managedObjectIDForURIRepresentation:uri];
NSManagedObject *myMO = [moc objectWithID:moID];

这篇关于NSManagedObjectID转换为NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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