Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get properties of NSManagedObject as NSDictionary

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.

like image 669
typeoneerror Avatar asked Apr 26 '12 21:04

typeoneerror


People also ask

What is a NSDictionary object?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.

Is NSDictionary ordered?

NSDictionary keys & values are not ordered.

How do I create an NSDictionary in Objective C?

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.

How do you convert NSDictionary to NSMutableDictionary?

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.


1 Answers

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];
like image 105
Frédéric Avatar answered Oct 14 '22 05:10

Frédéric