如何让NSTimer循环播放

pet*_*ete 0 macos objective-c nstimer foundation

我正在尝试学习NSTimer,使用Foundation和打印到控制台.任何人都可以告诉我我需要做些什么来让以下工作?它编译没有错误,但不激活我的startTimer方法 - 没有打印.

我的目标是让一个方法调用另一个方法来运行一些语句,然后在设定的时间后停止.

#import <Foundation/Foundation.h>

@interface MyTime : NSObject {
    NSTimer *timer;
}
- (void)startTimer;
@end

@implementation MyTime

- (void)dealloc {
    [timer invalidate];
    [super dealloc];
}

- (void)startTimer {
     timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(runTimer:) userInfo:nil repeats:YES];
}

- (void)runTimer:(NSTimer *)aTimer {
    NSLog(@"timer fired");
}
@end


int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];


    MyTime *timerTest = [[MyTime alloc] init];
    [timerTest startTimer];

    [timerTest release];

    [pool release];
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ell 6

计时器永远不会有机会在程序中触发,因为程序在创建计时器后几乎立即结束.

有一个名为Run Loop的结构,它负责处理输入,包括来自定时器的输入.为每个线程创建一个运行循环,但在这种情况下不会自动启动.

你需要运行run循环并保持运行直到计时器有机会发射.幸运的是,这很容易.插入:

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];
Run Code Online (Sandbox Code Playgroud)

之间发送startTimerreleasetimerTest.如果您希望重复计时器,则需要继续保持运行循环的活动状态.

请注意,您只需要在这样的简单程序中执行此操作; 当您使用GUI创建应用程序时,将通过Cocoa应用程序设置过程启动运行循环,并在应用程序终止之前保持活动状态.