Storing NSManagedObject in a dictionary (NSDictionary)

后端 未结 3 1798
闹比i
闹比i 2021-01-31 20:05

I have a custom class, which is a subclass of NSManagedObject. I would like to store it in a dictionary, but when trying to do so I receive a Property list in

相关标签:
3条回答
  • 2021-01-31 20:18

    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. Which won't work, because NSManagedObjects don't confirm to NSCoding.

    You could save the attributes of the NSManagedObject in a NSDictionary, and save this dictionary to a file..

    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:

    [myObject setValuesForKeysWithDictionary:dict];
    
    0 讨论(0)
  • 2021-01-31 20:24

    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. 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"];
    
    0 讨论(0)
  • 2021-01-31 20:27

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题