2012-04-04 48 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]; 

虽然你必须保持对定时器的引用来做到这一点,看起来你没有。