views:

694

answers:

4

I'm new to Objective C, and Mac development... It appears that I can use the Posix threads API in my app.. Is this the recommended way? Or is their some Apple API I should be using for mutexes, condition variables and threads instead?

I should add that I'm developing for the iPhone.

I'd like to add exactly what I'm trying to do. Basically, CoreLocation is asynchronous... You tell it to start updating you, and then it just calls an update method on you periodically...

The problem I have is that I need another thread to block until an update occurs... How can I make the main application thread block until at least one CoreLocation update occurs? Is their an NSConditionVariable? :)

+2  A: 

It depends on what you are trying to do, but I would start with NSOperation and NSOperationQueue. It makes it pretty simple to hand off background tasks. Take a look at Dave Dribin's blog post on NSOperation concurrency as well: http://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/

Matt Long
+5  A: 

I'd suggest an even easier way to get stuck into threads is to use the following call:

[self performSelectorInBackground:(@selector(myMethod)) withObject:nil];

This will automatically create a new background thread for you to run in. Incidentally make sure you do the following inside your background method:

-(void) myMethod {
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   // code you want to run in background thread;
   [pool drain];
}

This is necessary because there isn't a default autorelease pool set up for any threads except the main one.

Finally, talking about blocking the main thread, you could use the following from your background thread to do this:

[self performSelectorOnMainThread:(@selector(myOtherMethod)) withObject:nil waitUntilDone:YES];

The optional third parameter will hold up the main thread for you if you want it to do so.

Hope that helps!

h4xxr
+1 This was very useful. Thank you so much.
Oh Danny Boy
A: 

Yes there is an NSCondition object, and it will probably do exactly what you want for the CoreLocation scenario you mentioned.

Lounges
A: 

Instead of blocking the user interface by making it hang, I would suggest showing some kind of loading screen until you've received your first update. The could would look something like this:

- (void)viewDidLoad {
    ...
    [myCLLocationManager beginUpdates];
    [self showLoadingIndicator];
    ....
}

- (void)locationManager:(CLLocationManager *)manager didReceiveUpdates {
    [self hideLoadingIndicator];
    // Additionally load the rest of your UI here, if you haven't already
}

Don't quote me on those method calls verbatim, but that's how I suggest solving your problem, in essence.

jbrennan