2011-12-02 66 views
4

我創建一個NSTimer的NSTimer不通過參數選擇

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

createObject:定義如下:

- (void)createObject:(ccTime) dt{ 

    int r = arc4random() % 4; 


    for (int i=0; i < r; i++) { 

    character[charIndex] = [CCSprite spriteWithFile:@"o.png"]; 

    } 
} 

我想實現的是一些變量發送到方法。我重寫功能爲:

- (void)createObject:(ccTime) dt cID:(int)cID { 

    int r = arc4random() % 4; 


    for (int i=0; i < r; i++) { 

    character[cID] = [CCSprite spriteWithFile:@"o.png"]; 

    } 
} 

但我不能傳遞變量cID來自定時器的功能。是否有可能做到這一點?

回答

17

根據documentation方法是從一個叫的NSTimer需要這樣的簽名:

- (void)timerFireMethod:(NSTimer*)theTimer 

這是不可能提供自定義參數或多個參數。


因此重寫你的計時器方法,以便它使用的NSTimer

- (void)createObject:(NSTimer *)timer { 
    NSDictionary *userInfo = [timer userInfo]; 
    int cID = [[userInfo objectForKey:@"cID"] intValue]; 
    /* ... */ 
} 

創建一個用戶信息的用戶信息,然後開始像這樣的計時器:

NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys: 
          [NSNumber numberWithInt:cID], @"cID", 
          /* ... */ 
          nil]; 
[NSTimer scheduledTimerWithTimeInterval:2.0 
           target:self 
           selector:@selector(createObject:) 
           userInfo:userInfo 
           repeats:YES]; 
+1

5秒它說同樣的事情換句話說,+1 :) –

+0

唯一有效的簽名[根據文檔](http://developer.apple。com/library/mac /#documentation/Cocoa/Conceptual/Timers/Articles/usingTimers.html)是' - (void)meth:(NSTimer *)tim'。無參數版本似乎工作,但它是不正確的。 –

7

你的選擇必須具有此signature

- (void)timerFireMethod:(NSTimer*)theTimer 

但還有的UserInfo的可可概念

USERINFO:
定時器的用戶信息。您指定的對象由定時器保留,並在定時器失效時釋放。該參數可能爲零。

因此,很明顯,您可以使用它將信息傳遞給定時器調用的方法,並且可以通過該方法訪問UserInfo。

information = [theTimer userInfo]; 
+0

謝謝,這是非常有用的,但當我嘗試發送一個int值使用userInfo參數它給了我一個錯誤!我想如何發送信息? –

+0

它必須是一個對象,所以你需要在NSNunber中裝箱 –

0

userInfo參數必須是一個對象。其他數據類型(例如C數據tyoe)需要包裝在對象或字典或對象數組中。

0

您可以通過用戶信息的參數:[NSDictionary的dictionaryWithObjectsAndKeys:parameterObj1,@ 「keyOfParameter1」 ......

一個簡單的例子:比我更早的答案

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(handleTimer:) userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:9], @"parameter1", nil] repeats:YES]; 


-(void) handleTimer:(NSTimer *)timer{ 


    int parameter1 = [[[timer userInfo] objectForKey:@"parameter1"] integerValue]; 

    if(parameter1>0){ 

     [timer invalidate]; 
     timer=nil; 
    } 
}