如何让 NSTimer 循环 [英] How to get NSTimer to loop

查看:54
本文介绍了如何让 NSTimer 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 NSTimer,使用 Foundation 并打印到控制台.谁能告诉我我需要做什么才能使以下工作正常进行?它编译时没有错误,但不会激活我的 startTimer 方法——没有打印任何内容.

I'm trying to learn about NSTimer, using Foundation and printing to the console. Can anybody tell me what I need to do to get the following to work? It compiles with no errors, but does not activate my startTimer method -- nothing prints.

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

My aim is to get one method to call another method to run some statements, and then stop after a set time.

#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;
}

推荐答案

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

The timer never gets a chance to fire in your program, because the program ends almost immediately after the timer is created.

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

There's a construct called the Run Loop which is responsible for processing input, including input from timers. One run loop is created for each thread, but it isn't automatically started in this case.

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

You need to run the run loop and keep it going until the timer has a chance to fire. Fortunately, this is quite easy. Insert:

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5.0]];

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

between sending startTimer and release to timerTest. If you want the timer to repeat, you'll need to continue keeping the run loop active.

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

Note that you only need to do that in a simple program like this; when you are creating an application with a GUI, the run loop will be started via the Cocoa application setup process, and will remain active until the application terminates.

这篇关于如何让 NSTimer 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆