Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mchering

macrumors newbie
Original poster
Jan 17, 2009
3
0
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:in;

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

Can somebody help me with this?

Peter
 

mchering

macrumors newbie
Original poster
Jan 17, 2009
3
0
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

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

lee1210

macrumors 68040
Jan 10, 2005
3,182
3
Dallas, TX
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

macrumors newbie
Original poster
Jan 17, 2009
3
0
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

macrumors regular
Oct 13, 2008
144
0
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:

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

Code:
methodPtr(myObj, mySelector, valueForArg1, valueForArg2);

This should work for class methods too.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.