iPhone: how to use performSelector:onThread:withObject:waitUntilDone: method?

I found an answer!

In order to keep the thread up, there is a need in additional piece of code:

- (void)threadMain:(id)data {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSRunLoop *runloop = [NSRunLoop currentRunLoop];
    [runloop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];

    while (isAlive) { // 'isAlive' is a variable that is used to control the thread existence...
        [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    [pool release];
}

And the next line:

NSThread *myThreadTemp = [[NSThread alloc] init];

Should be replaced by this one:

NSThread *myThreadTemp = [[NSThread alloc] initWithTarget:self selector:@selector(threadMain:) object:nil];

EDIT: As was suggested by few people here I’ve added few lines of code (NSAutoreleasePool, addPort method and ‘isAlive’ boolean).

Leave a Comment