I need to create timers in another thread (not on main):
@implementation AppDelegate {
NSThread* _worker;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
_worker = [[NSThread alloc] initWithTarget:self selector:@selector(main) object:nil];
[_worker start];
}
- (void)main {
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(timer_tick:)
userInfo:nil
repeats:YES];
[NSThread sleepForTimeInterval:INFINITY];
NSLog(@"**********************");
}
- (void)timer_tick:(NSTimer*)timer {
NSLog(@"%@", NSThread.currentThread);
}
The timer never gets fired. What's wrong with my code?
You need to run a run loop in your thread. See: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html