简体   繁体   English

将NSManagedObject存储在字典中(NSDictionary)

[英]Storing NSManagedObject in a dictionary (NSDictionary)

I have a custom class, which is a subclass of NSManagedObject . 我有一个自定义类,它是NSManagedObject的子NSManagedObject I would like to store it in a dictionary, but when trying to do so I receive a Property list invalid for format: 200 error. 我想将它存储在字典中,但是当我尝试这样做时,我收到一个Property list invalid for format: 200Property list invalid for format: 200错误。

Here is how I try to create the dictionary: 以下是我尝试创建字典的方法:

NSDictionary *dictionary = 
    [NSDictionary dictionaryWithObject: voiceMemo forKey:@"voiceMemo"];

Same result when trying 尝试时结果相同

NSDictionary *dictionary = 
    [NSDictionary dictionaryWithObject: (NSData *) voiceMemo forKey:@"voiceMemo"];

It works, however, when trying to save the individual attributes separately: 但是,在尝试单独保存各个属性时,它可以正常工作:

NSDictionary *dictionary = 
    [NSDictionary dictionaryWithObject: voiceMemo.attribute forKey:@"attribute"];

NSDictionary should be able to store data objects, so I'm guessing, the real question is how to cast an NSManagedObject object to NSData NSDictionary应该能够存储数据对象,所以我猜,真正的问题是如何将NSManagedObject对象转换为NSData

Are you sure the error happens when you create the dictionary like it is implied by the code you have posted? 您确定在创建字典时发生了错误,就像您发布的代码所暗示的那样吗?

Property list invalid for format: 200 sounds like you try to write your NSManagedObject to the file system. Property list invalid for format: 200听起来像您尝试将NSManagedObject写入文件系统。 Which won't work, because NSManagedObjects don't confirm to NSCoding . 哪个不起作用,因为NSManagedObjects不确认NSCoding

You could save the attributes of the NSManagedObject in a NSDictionary, and save this dictionary to a file.. 您可以在NSDictionary中保存NSManagedObject的属性,并将此字典保存到文件中。

NSArray *keys = [[[myObject entity] attributesByName] allKeys];
NSDictionary *dict = [myObject dictionaryWithValuesForKeys:keys];

and when you want to restore it you set the values of your managedObject like this: 当你想要恢复它时,你可以像这样设置managedObject的值:

[myObject setValuesForKeysWithDictionary:dict];

A swift version in case anyone needs it 一个快速版本,以防任何人需要它

import CoreData 
extension NSManagedObject {
    func toDict() -> [String:Any] {
        let keys = Array(entity.attributesByName.keys)
        return dictionaryWithValues(forKeys:keys)
    }
}

In my app I'm also storing MO's in a dictionary (but no hold on, I'm storing in an array) but without any cast. 在我的应用程序中,我也将MO存储在字典中(但没有保留,我存储在数组中)但没有任何演员。 please try if this happens for an array too. 请尝试,如果这也发生在阵列上。

And you can try to create the dictionary first and after that assign objects. 您可以先尝试创建字典,然后再分配对象。

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:managedObject forKey:@"thisOne"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM