views:

50

answers:

2

I want to populate [MyClass class] from a JSON string.

I use json-framework to get the NSDictionary, and it's dead easy to instantiate and setValue: forKey:... on my data object.

But for more complex data objects with classes as members of MyClass,

ie:

MyOtherClass *classNoTwo

I tried with

Class test = object_getClass(myClass.classNoTwo);
id foo = [[test alloc] init];

But foo is nil/null. The only way I found to get around it is to in my init method of MyClass is to alloc memory for it, and later replace it.

I would also like to know how to get rid of the myClass.classNoTo reference, as I am not supposed to know all the properties in my general parser.

Please don't just tell me to read the documentation, because I've done that, and I can't figure it out.

Thanks in advance

+1  A: 

Try calling class_getProperty() to access a property of a particular name and then property_getAttributes() on the property returned by the first function. This will return a string that encodes the property's attributes, including the type. The format of the string is explained in Property Type Strings in the documentation.

Finally, when you have derived the type of the property, use NSClassFromString() to instantiate an object.

Also see the docs for the two functions mentioned for more details.

Ole Begemann
A: 

I have written a very simple dependency injection container called Factory. I do not get your question entirely, but the problems we solve look similar. Take a look at my sources, they are very simple and should get you started. You might be interested especially in the ClassAnalyzer class. It’s just a hack, but you should be able to get what you want from there.

zoul