19

我是一名新手IOS开发人员,但我在Android开发方面拥有丰富的经验。我的问题是关于间隔特定计时器的创建和使用。

在android中,我可以轻松地制作一个这样的计时器:

timedTimer = new Timer();
    timedTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            TimedMethod();
        }

    }, 0, 1000);

其中间隔为 1000 MS,并且 TimedMethod() 方法在每个刻度上调用。我将如何在 IOS 中实现类似的功能?

非常感谢您的阅读!任何帮助都会很棒!:-)

4

4 回答 4

43

您可以像这样使用重复NSTimer

- (void) startTimer {
   [NSTimer scheduledTimerWithTimeInterval:1 
                                    target:self 
                                  selector:@selector(tick:) 
                                  userInfo:nil
                                   repeats:YES];
}

- (void) tick:(NSTimer *) timer {
   //do something here..

}
于 2011-08-10T00:06:23.053 回答
5

利用

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];

在您调用上述方法的同一个类中,创建一个名为timerCallback. 每次定时器触发时都会调用它;每 1000 毫秒。

于 2011-08-10T00:08:43.637 回答
0

使用 Foundation Framework 的 NSTimer.h 文件中存在的以下方法

句法 :

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

用法 :

#define kSyncTimerLength 4 //Declare globally
-(void) timerActivityFunction; //Declare in interface

[NSTimer scheduledTimerWithTimeInterval:kSyncTimerLength target:self
        selector:@selector(timerActivityFunction) userInfo:nil repeats:NO];

-(void) timerActivityFunction {
     // perform timer task over-here   
}
于 2014-03-10T11:47:59.197 回答
0

对于斯威夫特:

使用下面的行创建一个计时器对象,它将每 10 秒调用一次上传方法。如果你得到没有实现 methodSignatureForSelector用 NSObject 扩展你的类。阅读此内容以获取更多信息Y 类的对象 X 未在 Swift 中实现 methodSignatureForSelector

 timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "upload", userInfo: nil, repeats: true)

func upload() {
        print("hi")
    }
于 2016-02-08T14:49:40.913 回答