Re: Obj-C language question: C function within @implementation
Re: Obj-C language question: C function within @implementation
- Subject: Re: Obj-C language question: C function within @implementation
- From: Greg Parker <email@hidden>
- Date: Thu, 3 Jul 2003 12:39:26 -0700
Sean McBride wrote:
> The error my coworker made (aside from step 3 itself :)) was to
> accidentally put the C function within the @implementation block, and
it
> staill compiles. I noticed this, and moved the C function out of the
> @implementation block and it stopped compiling. I'm wondering if it
> should never have compiled in the first place.
>
> @implementation MyController
>
> void pthread_start_routine (void* arg)
> {
> MyController* controller = (MyController*)arg;
> [controller->progressBar stopAnimation:controller];
> }
>
> @end
This is perfectly legal Objective-C code. Any code inside
@implementation is allowed to access protected instance variables,
whether the code is a function or a method. This is useful when writing
functions rather than methods for performance reasons or for C
callbacks like the case above.
There are two "cleaner" ways to do this that you may consider using.
One is to use an NSThread instead of pthread_create; NSThread invokes a
method instead of a function. The second is to rewrite the pthread
callback so that it does nothing but run a method:
@implementation MyController
void pthread_start_routine (void *arg)
{
MyController *controller = (MyController *)arg;
[controller runThread];
}
-(void) runThread
{
[progressBar stopAnimation:self];
}
@end
However, if the thread's content in your real code is as simple as this
example, then you may not want to bother creating a new method for that
single line of work that can be handled directly in the C callback
instead.
--
Greg Parker email@hidden Java & Objective-C
_______________________________________________
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.