Short Notes on MAC OSX

From PaskvilWiki
Revision as of 12:37, 11 December 2012 by Admin (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Asynchronous Execution

Here are 3 methods of executing code asynchronously.

Using NSThread (and threading in general) is the usual way, recommendable for longer-running threads.

The other 2 methods are typically recommended for use "locally", that is limited to the life-time of the object that spawns the async code.

NSThread

TODO

performSelectorInBackground:withObject:

The performSelectorInBackground method of NSObject spawns a new thread to execute your provided method (via selector).

This also means that you have to take care of your release's or create a release pool, just as with NSThread.

Typical usage:

- (void)mainMethod
{
    // ...
    [self performSelectorInBackground:@selector(asyncMethod:) withObject:someParam];
    // code here is executed (almost) immediately after the above call,
    // as the asyncMethod's code is now being executed in separate thread
    // ...
}
NSArray* foo = [[[NSArray alloc] initWithObjects:@"a", @"b", nil] autorelease];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];

- (void)asyncMethod:(id)param
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    // your code that will be executed asynchronously
    [pool release];
}

dispatch_async()

TODO