2014-01-22 40 views
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。

回答

4

userInfo應該是一本字典:

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

,你顯然需要改變你訪問它的選擇方式:

你需要調用dispatch_async()之前保留userInfo

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

該文檔聲明它應該是id。 https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSTimer_Class/Reference/NSTimer.html#//apple_ref/occ/instm/NSTimer/userInfo 即便如此,改變它到字典不會改變結果。 – MdaG

+0

@MdaG我已經更新了我的答案。您還需要以字典的形式訪問它。 – trojanfoe

+2

這裏的問題是,Timer會在mainThread中觸發'triggerTimer',並且您再次要求在maintherad上發送。所以派遣的工作將在下一次的循環中完成。但是定時器對象僅適用於此Runloop。 – chandu