2010-12-22 69 views
2

我正在嘗試製作一個非常簡單的遊戲,並且我被卡住了。基本上我想讓UIImageView每2秒出現一次。我的問題是我無法跟蹤累計時間。現在我有這個:目標C:不斷調用函數

NSDate *date = [NSDate date]; 

NSTimeInterval secondsSinceNow = [date timeIntervalSinceNow]; 

NSLog(@"date = %@", date); 
NSLog(@"secondsSinceNow = %f", secondsSinceNow); 

它在我的按鈕功能,所以它被稱爲當用戶點擊按鈕。它返回的小數始終小於1.我已經在viewDidLoad方法以及它自己的方法中嘗試過它,但都沒有成功。

我認爲它會工作,如果它在自己的方法是不斷檢查,但我不知道該怎麼做。

總之,我需要一個定時器/計數器,每秒更新一次。

回答

5
@interface className 
{ 
NSTimer * timer; 
} 

@property (nonatomic, retain) NSTimer * timer; 

@end 


@implementation className 
@synthesize timer; 

... 

/*工廠方法在此處得到糾正。通過複製和粘貼沒有警告應該工作*/

-(void) applicationDidFinishLaunching : (UIApplication *) application { 
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES]; 

} 

//define the target method 

/*,因爲它需要周圍的NSTimer括號法修正*/

-(void) targetMethod: (NSTimer *) theTimer { 
NSLog(@"Me is here at 1 minute delay"); 
} 
.. 
@end 

從這裏 http://www.iphonedevsdk.com/forum/iphone-sdk-development/14403-nstimer-examples.html

+0

工廠方法的名稱是錯誤的,正確的工廠方法稱爲scheduledTimerWithTimeInterval:target:selector:userInfo:repeatats: – LeonS 2012-05-28 06:59:01

0

您可以簡單地使用NSTimer以所需的兩秒間隔調用班級中的選擇器。

也就是說,您也可以使用CABasicAnimation來淡化UIImageView的不透明度,等待所需的效果。

0

採取了那些前兩行會立即被調用,那麼它(應該)總是小於一秒。日期正在被實例化,然後timeIntervalSinceNow被立即調用,當它們之間很少/沒有時間發生時。目標是首先調用日期,然後調用timeIntervalSinceNow以獲得大於0的時間。但是,這仍然沒有創建更新計時器。