View Full Version : Array of functions
mchering
Jan 17, 2009, 01:02 PM
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) = {
Item::createFromStream,
ItemB::createFromStream
};
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[i]:in;
But this gives me an "initializer element is not constant" error.
Can somebody help me with this?
Peter
Flynnstone
Jan 17, 2009, 02:52 PM
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.
mchering
Jan 17, 2009, 03:39 PM
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 :)
kpua
Jan 17, 2009, 05:57 PM
You probably want to use the SEL type and the @selector() directive.
lee1210
Jan 17, 2009, 06:02 PM
You probably want to use the SEL type and the @selector() directive.
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.
-Lee
mchering
Jan 18, 2009, 12:00 PM
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
Peter
autorelease
Jan 18, 2009, 03:56 PM
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.
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.