2012-04-04 25 views
0

Objective-C中的NSTimer有問題。這是我的源代碼: 的main.mNSTimer在xCode中無法在CMD項目中工作

#import <Foundation/Foundation.h> 
#import "TimerTest.h" 

int main(int argc, const char * argv[]) { 
    @autoreleasepool { 
     TimerTest *timerTest = [[[TimerTest alloc] init] autorelease]; 
    } 
    return 0; 
} 

TimerTest.h

#import <Foundation/Foundation.h> 

@interface TimerTest : NSObject { 
    NSTimer *_timer; 
} 
@property (nonatomic, retain) NSTimer *timer; 
- (id) init; 
@end 

TimerTest.m

#import "TimerTest.h" 

@implementation TimerTest 
@synthesize timer = _timer; 
- (id) init { 
    if (self = [super init]) { 
     [NSTimer timerWithTimeInterval:0.5f 
           target:self 
           selector:@selector(tick:) 
           userInfo:nil 
           repeats:YES]; 
    } 
    return self; 
} 

- (void) tick: (NSDate *) dt { 
    NSLog(@"Tick! \n"); 
} 

- (void) dealloc { 
    self.timer = nil;  
    [super dealloc]; 
} 
@end 

我的程序應該記錄每0.5秒 「嘀\ n」! 。但後來我的程序完成了,xcode控制檯很清楚,這就是NSLog-(void)tick:(NSDate *)dt方法沒有用。我的錯誤在哪裏?

回答

1

我的程序應該每0.5秒記錄一次「Tick!\ n」。

不,它不應該(至少不是根據您發佈的代碼)。你需要一個run loop。定時器僅作爲運行循環中的事件激發。所以,在你的主體中,你需要設置一個並運行它。

0

您不僅需要事件循環,而且還創建了一個計時器,並且您尚未在所述運行循環中安排它。相反的:

[NSTimer timerWithTimeInterval:0.5f 
          target:self 
          selector:@selector(tick:) 
          userInfo:nil 
          repeats:YES]; 

做到這一點:

[NSTimer scheduledTimerWithTimeInterval:0.5f 
            target:self 
            selector:@selector(tick:) 
            userInfo:nil 
            repeats:YES]; 

我設置在Cocoa應用程序的(因爲它帶有一個運行循環)的情況下你的代碼了,在的的applicationDidFinishLaunching執行TimerTest分配代表,和你的代碼,否則工作。

一對夫婦的其他東西:該方法,其選擇傳遞給scheduledTimerWithTimerInterval:......應該是這樣的形式

- (void)timerMethod:(NSTimer *)aTimer 

,當你與你的計時器完成,只是使它無效:

[timer invalidate]; 

雖然你必須保持對定時器的引用來做到這一點,看起來你沒有。

相關問題