If I have an NSManagedObject I've fetched from a context, how can I create an NSDictionary out of its dynamic properties without just copying each field into the dictionary explicitly?
If my managed object looks like this, for example:
@implementation Track
@dynamic artist;
@dynamic group;
@dynamic purchase_url;
@dynamic title;
@dynamic file_name;
@dynamic year;
@end
After fetching from the database, in this case, I need an NSDictionary with the same properties set to each of those @dynamic properties.
An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.
NSDictionary keys & values are not ordered.
Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.
Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.
There is a faster way to convert an NSManagedObject to an NSDictionary (from Matthias Bauch response at https://stackoverflow.com/a/5664745/2294824) :
NSArray *keys = [[[myObject entity] attributesByName] allKeys];
NSDictionary *dict = [myObject dictionaryWithValuesForKeys:keys];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With