2012-06-21 25 views
3

我使用NSTimer來運行動畫(現在只需將其稱爲myMethod)。但是,它導致了崩潰。NSTimer在啓動時導致「無法識別的選擇器」崩潰

下面的代碼:

@implementation SecondViewController 


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 


- (void) myMethod 
{ 
    NSLog(@"Mark Timer Fire"); 

} 


- (void)viewDidLoad 
{ 
[super viewDidLoad]; 



NSLog(@"We've loaded scan"); 

[NSTimer scheduledTimerWithTimeInterval:2.0 
           target:self 
           selector:@selector(myMethod:) 
           userInfo:nil 
           repeats:YES]; 

animationTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(myMethod:) userInfo:nil repeats: YES]; 


} 

而這裏的崩潰

期間的輸出 - [SecondViewController myMethod的:]:無法識別的選擇發送到實例0x4b2ca40 2012-06-21 12:19 :53.297測謊器[38912:207] *因未捕獲異常'NSInvalidArgumentException'而終止應用程序,原因:' - [SecondViewController myMethod:]:無法識別的選擇器發送到實例0x4b2ca40'

那麼我在這裏做錯了什麼?

回答

4

要麼你只能使用

- (void)myMethod: (id)sender 
{ 
// Do things 
} 

,或者你可以做(​​刪除:從兩個方法名)..

animationTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(myMethod) userInfo:nil repeats: YES]; 

希望這將幫助你

+0

第一個選項是正確的,只不過參數應該被輸入爲'(NSTimer *)'。 –

3

通過此

[NSTimer scheduledTimerWithTimeInterval:2.0 
          target:self 
          selector:@selector(myMethod) 
          userInfo:nil 
          repeats:YES]; 
+2

這是一個很好的答案,我不明白他們爲什麼低估這一點。 +1賠償。 – 2012-06-27 06:13:33

2

計時器的動作方法should take one argument替換此

[NSTimer scheduledTimerWithTimeInterval:2.0 
          target:self 
          selector:@selector(myMethod:) 
          userInfo:nil 
          repeats:YES]; 

- (void)myMethod: (NSTimer *)tim 
{ 
    // Do things 
} 

此方法的名稱爲myMethod:,包括結腸。您當前的方法名稱是myMethod,而不是冒號,但您通過傳遞具有該方法的名稱來創建計時器:selector:@selector(myMethod:)

當前,定時器將消息myMethod:發送給您的對象;你的對象沒有迴應(但會迴應myMethod)並引發異常。

5

我跑進這個問題同時使用Swift。在Swift中,我發現NSTimer的目標對象必須是NSObject纔可能不明顯。

class Timer : NSObject { 
    init() { super.init() } 
    func schedule() { 
     NSTimer.scheduledTimerWithTimeInterval(2.0, 
          target: self, 
          selector: "myMethod", 
          userInfo: nil, 
          repeats: true) 
    } 
    func myMethod() { 
    ... 
    } 
} 

希望這有助於某人。

+0

你剛剛救了我幾個小時..謝謝 –

相關問題