NSRunloop in Thread

1.9k Views Asked by At

I get a problem

here is the code

- (void)start{
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];
}

- (void)nlog{
    NSLog(@"cool");
}


- (void)main{



    thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];

    [thread start];


    [self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];
}

when I call

[self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];

the thread will keeping running and I can do something in the thread later;

but if I don't call it, the thread will exit at once and can never use the thread do anything, why?

2

There are 2 best solutions below

0
On

When you start a thread, if you don't add any source to the runloop, the run loop will return immediately. Then the thread finished.

Check out:

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1

3
On

Firstly, I don't think you have correct idea on using thread:

thread = [[NSThread alloc] initWithTarget:self selector:@selector(start) object:nil];

[thread start];

Do not override the 'start' method of NSThread, you should override the 'main' method.

Secondly, if you want to create run loop in a thread, there should be a while loop, like this:

while (condition)
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];

BTW, please refer to my answer for more details usage of NSRunLoop: Best way to make NSRunLoop wait for a flag to be set?