Say you attach a timer to a runloop in a particular thread but the thread has exited before the timer gets triggered, causing the method to not be executed. Is this scenario possible?

有帮助吗?

解决方案

Certainly this is possible, and it's easy enough to demonstrate.

#import <Foundation/Foundation.h>

#define TIMER_INTERVAL 2.0

@interface Needle : NSObject

- (void)sew;
- (void)tick:(NSTimer *)tim;

@end

@implementation Needle
{
    NSTimer * tim;
}

- (void)sew
{
    @autoreleasepool{
        tim = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
                                               target:self
                                             selector:@selector(tick:)
                                             userInfo:nil
                                              repeats:NO];

        while( ![[NSThread currentThread] isCancelled] ){
            [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
        }
    }
}

- (void)tick:(NSTimer *)timer
{
    NSLog(@"Let's get the bacon delivered!");
    [[NSThread currentThread] cancel];
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        Needle * needle = [Needle new];
        NSThread * thread = [[NSThread alloc] initWithTarget:needle
                                                    selector:@selector(sew)
                                                      object:nil];

        [thread start];
        // Change this to "+ 1" to see the timer fire.
        NSTimeInterval interval = TIMER_INTERVAL - 1;
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:interval]];
        [thread cancel];

    }
    return 0;
}

其他提示

Yes, unless you are on the main thread, there is no NSRunLoop keeping the thread alive and for the timers to attach to. You'll need to create one and let it run.

Yes it is. This happens quite easily, if there is a timer but the app quits "prematurely". In this case, the timer's fire date will be lost - even when the app gets restarted before the timer's fire date that has been set formerly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top