2014-01-08 108 views
1

我在iOS 7上使用+[NSTimer scheduledTimerWithTimeInterval:invocation:repeats]時遇到了崩潰。代碼很簡單;這裏是複製粘貼(帶有變量重命名)。NSTimer + NSInvocation導致iOS 7崩潰

SEL selector = @selector(callback); 
NSMethodSignature *signature = [self methodSignatureForSelector:selector]; 
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
[invocation setTarget:self]; 
[NSTimer scheduledTimerWithTimeInterval:0.5 invocation:invocation repeats:NO]; 

當計時器火災,我的應用程序崩潰,並顯示以下堆棧跟蹤:

enter image description here

我認爲變量的可能之一是不再保留(即使的NSTimer的文檔中提到它保留所有參考參數),所以我強烈保留所有變量到self。不幸的是,崩潰依然存在。

在此先感謝!

回答

2

你缺少這一行[self.invocation setSelector:selector];

這將工作

SEL selector = @selector(callback); 
NSMethodSignature *signature = [self methodSignatureForSelector:selector]; 
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; 
[invocation setTarget:self]; 
[invocation setSelector:selector]; 
[NSTimer scheduledTimerWithTimeInterval:0.5 invocation:invocation repeats:NO]; 

- (void)callback 
{ 
    NSLog(@"triggered"); 
} 

輸出:

triggered 
+0

謝謝!這工作。我應該更仔細地閱讀文檔。 :) –

+0

當然......... :) –

1

This answer似乎在暗示你需要調用setSelector:上除了調用用簽名來啓動它。

+0

歡迎來到SO!這通常是普通的禮貌(如果它不是一個規則的話)讓任擇議定書知道他的問題是否重複。你發佈的答案應該是你自己的。這樣,如果您鏈​​接的答案有效,他可以對答案進行投票,並且信用可以發送給正確的人。 – CaptJak

+0

OP代表什麼?我該怎麼讓她知道?評論這個問題? –

+0

OP是原創帖子(或海報)。你是對的,對這個問題發表評論。我並非試圖阻止你回答,甚至不讓你刪除這個答案。只是一個關於回答問題的指示:) – CaptJak