Re: Passing C Style Function Callbacks in Cocoa
Re: Passing C Style Function Callbacks in Cocoa
- Subject: Re: Passing C Style Function Callbacks in Cocoa
- From: John Nairn <email@hidden>
- Date: Fri, 5 Mar 2004 09:56:16 -0700
On Mar 5, 2004, at 8:42 AM, email@hidden wrote:
'm a Object C newbie and hope someone here can help. I need to pass a
function call-back to a C- style function from one of my objects. I
have declared the call-back function before the @implementation MyObj.
The problem I'm having is accessing my object from within the call-back
function, which doesn't seem to know about my object. I want the
callback to send a setter message to my object. I'd rather be able to
pass a call-back that was a method of my object instead. Is there a way
to pass a Obj C style message as a function* in place of the C-style
function???
There are probably several solutions, but one I found very powerful was
to set up a delegate option analogous to many Cocoa classes. You set
the delegate of an object which will be the object to receive the call
backs. The object making the callbacks can then inquire of the delegate
if it supports any method (try to create an NSMethodSignature using
[delegate methodSignatureForSelector:mySelector]). If it has the method
you can create an NSInvocation for that signature, set its target to
the delegate, and its selector to the method you want to call.
NSInvocation *newMethod=[NSinvocation
invocationWithMethodSignature:signature];
[newMethod setTarget:delegate];
[newMethod setSelector:mySelector];
Finally, when you want to do a callback, fill in any number of
arguments and "invoke" that NSInvocation.
I used this method to make a custom parser for GEDCOM genealogy files.
It sends call backs as it encounters new records, new lines of data,
errors in the data, or various other data-specific items. It is similar
to some built-in Cocoa parsers such as the XML parser, but customized
for the data type I am reading. The method is very general.
------------
John Nairn (1-801-581-3413, FAX: 1-801-581-4816)
Web page:
http://www.eng.utah.edu/~nairn
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.