initWithTarget:selector:object:
Returns an
NSThread
object initialized with the given arguments.
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
Parameters
- target
- The object to which the message specified by selector is sent.
- selector
- The selector for the message to send to target. This selector must take only one argument and must not have a return value.
- argument
- The single argument passed to the target. May be
nil
.
Return Value
An
NSThread
object initialized with the given arguments.Discussion - [NSThread initWithTarget: selector: object:]
For non garbage-collected applications, the method selector is responsible for setting up an autorelease pool for the newly detached thread and freeing that pool before it exits. Garbage-collected applications do not need to create an autorelease pool.
The objects target and argument are retained during the execution of the detached thread. They are released when the thread finally exits.
Example
#import <Foundation/Foundation.h>
#define NOT_DONE 0
#define DONE 1
// this will need to be on some class that is calling the NSThread object
-(void) someFunc:(id) arg {
NSConditionLock* myLock = arg;
[myLock lock];
//do stuff that we need to know about in main
[myLock unlockWithCondition:DONE];
}
int main() {
NSConditionLock* finishedLock = [[NSConditionLock alloc]
initWithCondition: NOT_DONE];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(someFunc:) object:finishedLock];
[myThread start];
[finishedLock lockWhenCondition:DONE];
// now we can do whatever we need to do with the results from
// the thread we spawned
}