views:

546

answers:

6

I want to know how I can run a method in a separate thread? Class & Method references. Thanks.

+2  A: 

Found the answer (you can use either of these statements to achieve this):

[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

OR

NSThread *myThread = [[NSThread alloc] initWithTarget:self
                     selector:@selector(myThreadMainMethod:) 
                     object:nil]; 
[myThreadstart];
Mustafa
+2  A: 

Another alternative is

[someObject performSelectorInBackground:@selector(someSelector:) 
     withObject:nil];

chris.

PyjamaSam
+1  A: 

If you've already created an NSThread and you've held onto the NSThread object, you can subsequently send more messages to be performed on that thread using:

–[NSObject performSelector:onThread:withObject:waitUntilDone:]
Matt Gallagher
+1  A: 

Question: When i start a new method in a separate thread, why do i need an NSAutoreleasePool object in that method? If i don't add it, i get a Pool Stack in the log.

Mustafa
+1  A: 

You need a new auto release pool to handle all the auto releasing in that thread. The main thread has one that is created automatically by the framework before you get to your code.

Also make sure if you are doing any interface updateing that you delegate it back to the main thread. The update may or may not work if you don't

[self performSelectorOnMainThread:@selector(someSelector:) 
         withObject:passedInObject waitUntilDone:NO];

chris.

PyjamaSam
+1  A: 

Found the answer to my own question:

When i start a new method in a separate thread, why do i need an NSAutoreleasePool object in that method? If i don't add it, i get a Pool Stack in the log.

Autorelease Pools and Thread (MemoryMgmt.pdf from Apple.com):

Each thread in a Cocoa application maintains its own stack of NSAutoreleasePool objects. When a thread terminates, it automatically releases all of the autorelease pools associated with itself. Autorelease pools are automatically created and destroyed in the main thread of applications based on the Application Kit, so your code normally does not have to deal with them there. If you are making Cocoa calls outside of the Application Kit's main thread, however, you need to create your own autorelease pool. This is the case if you are writing a Foundation-only application or if you detach a thread.

Mustafa