0
我有這段代碼。無法訪問NSTimer的userInfo
- (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。
該文檔聲明它應該是id。 https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSTimer_Class/Reference/NSTimer.html#//apple_ref/occ/instm/NSTimer/userInfo 即便如此,改變它到字典不會改變結果。 – MdaG
@MdaG我已經更新了我的答案。您還需要以字典的形式訪問它。 – trojanfoe
這裏的問題是,Timer會在mainThread中觸發'triggerTimer',並且您再次要求在maintherad上發送。所以派遣的工作將在下一次的循環中完成。但是定時器對象僅適用於此Runloop。 – chandu