Array of functions

Discussion in 'Mac Programming' started by mchering, Jan 17, 2009.

  1. macrumors newbie

    Jan 17, 2009
    Hello everyone,

    I have a problem on how to implement an array of functions like it would look like in C++ code:

    static Item* (*chunkProcs[nrOfItemTypes])(QDataStream* in) = {

    How should this look like in Objective-C ?

    I tried something like this:

    static Item* (*chunkProcs[nrOfItemTypes])(NSMutableData* in) = {
    [Item createFromStream],
    [ItemB createFromStream]

    and used this array like this:

    Item* item = chunkProcs:in;

    But this gives me an "initializer element is not constant" error.

    Can somebody help me with this?

  2. macrumors 65816


    Feb 25, 2003
    Cold beer land
    Not sure if I can help exactly, but ...

    Objective -C is C.
    So you should be able to have an array of pointers to functions. C style.
  3. thread starter macrumors newbie

    Jan 17, 2009
    Thanks for your reply, I also think that this should be possible with Objective-C but at the moment I don't get the right syntax for that problem :)
  4. macrumors 6502

    Jul 25, 2006
    You probably want to use the SEL type and the @selector() directive.
  5. macrumors 68040


    Jan 10, 2005
    Dallas, TX
    I thought this, too, but it seems that the OP is wanting to call factory methods in this way, and I honestly didn't know if you could get a SEL for a class method, and invoke it with NSInvocation (with the target as a class?), and NSObject's performSelector is an instance method. I started writing something up, but it got long, then i realized it might not even work for a factory method and gave up (finding myself too lazy, on a sit-around Saturday, to try it).

    I still don't know, after a few searches, if you can use class methods with this method. I would almost be inclined to have regular C functions that call the class methods and return the result, and keep pointers to those functions, but that isn't very fun.

  6. thread starter macrumors newbie

    Jan 17, 2009
    perhaps it is realisable with implementation pointers?
    Does anybody have an example for using them? Unfortunately i could only find some usenet faqs and they were not very comprehensible to me

  7. macrumors regular

    Oct 13, 2008
    Achewood, CA
    An IMP is a pointer to a function that returns an id and takes (id, SEL, ...) as its arguments.

    You get an IMP from a selector like this:

    SEL mySelector = @selector(someMethodWithArg1:arg2:);
    IMP methodPtr = [myObj messageForSelector:mySelector];
    Then you call the method by dereferencing the function pointer. The first argument is self, the second is _cmd, and the other arguments follow.

    methodPtr(myObj, mySelector, valueForArg1, valueForArg2);
    This should work for class methods too.

Share This Page