Run a method in a separate thread in Objective-C (Cocoa Framework)

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

	// Perform search in a separate thread
	[NSThread detachNewThreadSelector:@selector(performSearch:) toTarget:self withObject:nil];

The method

-(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.

One Comment

  1. Posted February 13, 2012 at 6:55 pm | Permalink

    I always have to code the entire app then put it into threads because my brain jsut doesn’t like think in them.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?