View Full Version : How create a object from the class dynamically?

Jan 8, 2009, 10:04 AM

I'm building my first iPhone app, and for learning (& because I don't find a good ORM layer) I'm building the ORM part.

I have 10+ years of experience coding in FoxPro, Delphi, .NET, Python, but this Obj-C is the most confusing of all :D

In Delphi or .NET I can do this:

function Select(sql:String,TClass):TArray;

Is important to note that I pass the class, nor a instantiated object. Now, inside select, I do TClass.Create(..) & get a new object...

How mimic this in Obj-c?

-(NSArray *) load: (NSString *)sql :(DbObject)obj;

This not work...

Jan 8, 2009, 01:04 PM
From your example, it looks like you know the type of the object - so what's wrong with creating the object outside the method? Alloc and init the object, and then pass it into the method. (I'm assuming the object is of type DbObject every time; not true?)

So will this work?

//calling the method
obj = [[DBObject alloc] init];
[self load: sql inObj: obj];

//defining the method
-(NSArray *) load: (NSString *)sql inObj:(DbObject*)obj;{
//do stuff with obj

If the objects really are of different types, and the type changes at runtime, there's a method and example code in NSBundle for loading a class dynamically - but that doesn't seem necessary here.

Jan 8, 2009, 02:10 PM
Mmmm... no, the idea is do something like:

for row in rows
ob = TClass.Create...
Db.Fill(ob, row)
array.Add( ob )

So, if a pass the object, I get the same reference in all the rows of the array.

Jan 9, 2009, 12:41 AM
Gotcha. You'll be creating more than one object, so you want to do the alloc and init inside the loop.

If the type is going to change at runtime, see the example code in NSBundle. You can pass a string with the class name into the method. Otheriwse, if the type is always the same, just hardcode it in the loop.