I want to know how I can run a method in a separate thread? Class & Method references. Thanks.
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];
Another alternative is
[someObject performSelectorInBackground:@selector(someSelector:)
withObject:nil];
chris.
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:]
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.
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.
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.