views:

50

answers:

2

Hi,

(New to Objective-C, but well versed in C/C++).

Presently I have an Objective-C class and a number of its member variables will be function pointers. These function pointers will only be modified by the class itself, but may be used by other classes.

I'm not sure how to set up access to said function pointers.

The solution I currently envision is to declare said function pointers @public, which as I understand it will allow me to call them using the -> operator. This seems fairly unsatisfactory to me, since the function pointers are left open to meddling, and it flies in the face of sound OOP.

My next inclination is toward using @property, and declaring them read only. This seems more sane. I assume I'd call them using the dot operator, as the idea of using to getter to get the function pointer and then call it seems entirely ludicrous.

Can one use function pointers as properties? If so, how would I go about declaring these to be properties:

void (*sort)(SET, int) ;
char *(*toASCII)(CARD) ;

I have a feeling I'm missing a slight nuance to declaring these as properties.

A: 

I believe you should be able to use function pointers as properties. You'd do it like this:

@property (nonatomic, readonly) char *(*toASCII)(CARD);

And then in your implementation:

@synthesize toASCII;

Then

object.toASCII();
jtbandes
Thanks, this looks good. Any specific reason for nonatomic? I'm assuming it's because it's readonly, and I don't have to worry about lost updates. If I understand correctly this should perform better than if it were left atomic.
John Carter
From what I understand, atomic vs nonatomic doesn't make a difference when doing readonly properties. And, for pointers and scalars, nonatomic and atomic accessors are the same anyway (a write to a pointer or a 32-bit value is atomic because it takes a single processor instruction). However, in general, nonatomic accessors perform better than atomic ones because it takes more effort to do the locking etc required to create an atomic accessor.
Jacques
A: 

In your @interface:

@property(readonly) void (*sort)(SET, int);
@property(readonly) char *(*toASCII)(CARD);

In your @implementation:

@synthesize sort, toASCII;

In your init method (or wherever else you want to set the function pointers):

sort = someFunction;
toASCII = someFunction;

On modern versions of iOS, you don't even need to add an ivar (it gets added automatically for you when you do @synthesize).

Jacques
Thanks for the tip on not adding the instance variables, makes things look a bit nicer.
John Carter