How create a object from the class dynamically?

Discussion in 'iOS Programming' started by mamcx, Jan 8, 2009.

  1. macrumors regular

    Joined:
    Mar 13, 2008
    #1
    Hi,

    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:

    Code:
    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?

    Code:
    -(NSArray *) load: (NSString *)sql :(DbObject)obj;
    This not work...
     
  2. macrumors regular

    xsmasher

    Joined:
    Jul 18, 2008
    #2
    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?
    Code:
    
    //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.
     
  3. thread starter macrumors regular

    Joined:
    Mar 13, 2008
    #3
    Mmmm... no, the idea is do something like:

    Code:
    for row in rows
        ob = TClass.Create...
        Db.Fill(ob, row)
        array.Add( ob )
    next
    
    So, if a pass the object, I get the same reference in all the rows of the array.
     
  4. macrumors regular

    xsmasher

    Joined:
    Jul 18, 2008
    #4
    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.
     

Share This Page