无法访问NSTimer的userInfo

时间:2014-01-22 09:58:17

标签: objective-c ios7 automatic-ref-counting nstimer

我有这段代码。

- (void)scheduleTimerAfterDelay:(NSTimeInterval)delay {
    dispatch_async(dispatch_get_main_queue(), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:delay
                                                  target:self
                                                selector:@selector(triggerTimer:)
                                                userInfo:[NSString stringWithFormat:@"%f", delay]
                                                 repeats:NO];
    });
}

- (void)triggerTimer:(NSTimer *)timer {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Triggered timer after %@ s.", _timer.userInfo); // <-- Exception thrown!
        // Do stuff
    });
}

但是当计时器触发时,_timer.userInfo会导致Exception: EXC_BAD_ACCESS (code=1, address=0xc))

我错过了什么?在异常行的断点处打印_timer表明_timer是<__NSCFTimer: 0x14ec8cb0>。但我也无法通过lldb访问userInfo。我正在使用ARC。

1 个答案:

答案 0 :(得分:5)

userInfo应该是字典:

_timer = [NSTimer scheduledTimerWithTimeInterval:delay
                                          target:self
                                        selector:@selector(triggerTimer:)
                                        userInfo:@{ @"name" : @"Zinedine Zidane",
                                                    @"age"  : @42 }
                                         repeats:NO];

你显然需要改变你在选择器中访问它的方式:

在致电userInfo之前,您需要保留dispatch_async()

- (void)triggerTimer:(NSTimer *)timer {
    NSString *s = timer.userInfo;    // Strong reference!
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Triggered timer after %@ s.", s);
        // Do stuff
    });
}