Difference between revisions of "Short Notes on MAC OSX"

From PaskvilWiki
Jump to: navigation, search
 
Line 8: Line 8:
  
 
=== NSThread ===
 
=== NSThread ===
 +
 +
'''TODO'''
  
 
=== performSelectorInBackground:withObject: ===
 
=== performSelectorInBackground:withObject: ===
Line 36: Line 38:
  
 
=== dispatch_async() ===
 
=== dispatch_async() ===
 +
 +
'''TODO'''

Latest revision as of 12:37, 11 December 2012

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