Friday, March 30, 2012

Run a method in a separate thread in Objective-C


In some situations, performing operations in a single thread can cause an application to appear as if it is hanging. For example, when searching with autocomplete enabled within a large amount of records in a database .

Searching with autocompletion enabled
The user is typing and the application is performing a computationally complex operation at the same time (searching within a huge amount of records). By dividing keyboard handling and searching into separate threads, the application will not appear as if it is hanging. Keyboard handling and searching can then be performed ‘simultaneously’.
The following snippets demonstrate the execution of a method within a separate thread.
The initial call
?
1
2
// Perform search in a separate thread
[NSThread detachNewThreadSelector:@selector(performSearch:) toTarget:self withObject:nil];
The method
?
1
2
3
4
5
6
7
8
-(void)performSearch:(id)sender {
    NSAutoreleasePool *autoReleasePool = [[NSAutoreleasePool alloc] init];
    // Perform a search operation here
    [NSThread exit];
    [autoReleasePool release];
}
This entry was posted in Objective-C and tagged ,. Bookmark the permalink. Trackbacks are closed, but you can post a comment.
references
-http://snipd.net/run-a-method-in-a-separate-thread-in-objective-c-cocoa-framework