How to get NSRunLoop to work inside a separate thread?

Take a look at this code:

@interface myObject:NSObject -(void)function:(id)param; @end @implementation myObject -(void)function:(id)param { NSLog(@"BEFORE"); [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:20]]; NSLog(@"AFTER"); } @end int main(int argc, char *argv[]) { myObject *object = [[myObject alloc] init]; [NSThread detachNewThreadSelector:@selector(function:) toTarget:object withObject:nil]; @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } 

The function method is called, but there is no pause in 20 seconds. What to do to make NSRunLoop work in a separate thread?

+4
source share
1 answer

Since you use the function: selector in another thread, [NSRunLoop currentRunLoop] does not match the main thread.

See NSRunLoop Link :

If no sources or timers are connected to the start loop, this method ends immediately

I assume your launch cycle is empty, and so the BEFORE and AFTER logs will appear instantly.

A simple solution to your problem would be

 @implementation myObject -(void)function:(id)param { NSLog(@"BEFORE"); [[NSRunLoop currentRunLoop] addTimer:[NSTimer timerWithTimeInterval:20 selector:... repeats:NO] forMode:NSDefaultRunLoopMode]; [[NSRunLoop currentRunLoop] run]; NSLog(@"AFTER"); } @end 

In fact, you probably put the code that registers AFTER in the new method that your timer calls. In general, you do not need threads for animation (unless you are doing something expensive). If you are doing expensive things from a computational point of view, you should also consider using Grand Central Dispatch (GCD), which simplifies the calculations for loading background threads and will handle the plumbing for you.

+4
source

Source: https://habr.com/ru/post/1402846/


All Articles