0

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?

Siverchen
  • 379
  • 2
  • 16
  • Try [self performSelector:@selector(start) onThread:thread withObject:nil waitUntilDone:NO]; I don't think you are starting that run loop on the correct thread. – sbarow Aug 16 '13 at 11:57
  • @sbarow I think the run loop do starting on the secondary thread, if not maybe the thread will not running whatever the nlog is called or not – Siverchen Aug 16 '13 at 12:07
  • Easy way to check is give your thread a name [thread setName:@"MyThread"]; and then in **start** and **nlog** log the thread NSLog("%@", [NSThread currentThread]); – sbarow Aug 16 '13 at 12:16

2 Answers2

0

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

hrchen
  • 1,223
  • 13
  • 17
-1

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?

Community
  • 1
  • 1
Richard
  • 339
  • 3
  • 10
  • 1
    if you put `runUntilDate:` in a while loop, you should replace `[NSDate distantFuture]` to something like `[NSDate dateWithTimeIntervalSinceNow:1]` – Bryan Chen Aug 18 '13 at 09:30
  • 1
    As sometimes `runUntilDate:` may not return because it is still waiting for next input source, add a limit date to guarantee its return. – Richard Aug 18 '13 at 12:11
  • @Richard I think you are right and I think just `[self performSelector:@selector(nlog) onThread:thread withObject:nil waitUntilDone:NO];` do the work for delaying the time to guarantee the return – Siverchen Aug 19 '13 at 03:50