I have an issue where I am getting in an object of type id. i know its base type is an NSManagedObject but the custom attributes for whatever type it actually is (name, email, etc) are what i really need. in the long run, i am trying to make one method that will turn my custom NSManagedObjects into NSDictionaries. maybe i am going down the wrong path in general but….
If i have something like
-(void)someMethod:(id)obj{
...
Class someClass = NSClassFromString([[obj class] description]);
...
i can get the class from that but then i cannot really figure out how to cast my object as that class.
ideally this would be the next few lines of that code
someClass* myObject = (someClass*)obj;
NSArray *keys = [[[myObject entity] attributesByName] allKeys];
NSDictionary *dict = [myObject dictionaryWithValuesForKeys:keys];
//do something with dict
...
but i cannot figure out how to get an object of the type someClass. I have seen where you can use the NSClassFromString object for an alloc init call like
id someObject = [[className alloc] init];
but that will not work for this situation as i already have an object passed in that I need. any ideas / criticisms? I am really trying to avoid a crap load of if statements for all of my items but it may be the quickest way right now…
If they are all NSManagedObject subclasses, and all you will be calling on them is valueForKey or other methods that are implemented by NSManagedObject, just cast to NSManagedObject. If I’m missing something, please let me know.
In answer to your comment on the original question – you already have this in your sample:
This gives you a dictionary containing all the attributes of your managed object, with the attribute name as the key in each case. You then use these keys to call valueForKey on your object.
Perhaps a point I need to make is that it is fine to cast an object as its superclass, if you are not going to call any subclass specific methods on it.