麻烦NSTimer

时间:2012-06-03 23:33:58

标签: objective-c xcode cocoa

我在NSTimers遇到这么多麻烦。我之前使用过它们,但这个计时器根本不想开火。

-(void) enqueueRecordingProcess
{
    NSLog(@"made it!");
    NSTimer *time2 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(warnForRecording) userInfo:nil repeats:YES];

}

-(void) warnForRecording
{
    NSLog(@"timer ticked!");
    if (trv > 0) {
        NSLog(@"Starting Recording in %i seconds.", trv);
    }
}

我不明白为什么这不会运行。我甚至试过这个:

- (void)enqueueRecordingProcess
{
    NSLog(@"made it!");
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(warnForRecording) userInfo:nil repeats:YES];
}

 - (void)warnForRecording
{
    NSLog(@"timer ticked!");
}

有什么问题?

3 个答案:

答案 0 :(得分:2)

不确定这是否会修复它,而是来自docs

The message to send to target when the timer fires. The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
The timer passes itself as the argument to this method.

答案 1 :(得分:0)

我不确定你的具体细节,但是你需要为runloop提供服务以获取事件,包括计时器。

答案 2 :(得分:0)

// Yes.  Here is sample code (tested on OS X 10.8.4, command-line).
// Using ARC:
// $ cc -o timer timer.m -fobjc-arc -framework Foundation
// $ ./timer
//

#include <Foundation/Foundation.h>

@interface MyClass : NSObject
@property NSTimer *timer;
-(id)init;
-(void)onTick:(NSTimer *)aTimer;
@end

@implementation MyClass
-(id)init {
    id newInstance = [super init];
    if (newInstance) {
        NSLog(@"Creating timer...");
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0
            target:self
            selector:@selector(onTick:)
            userInfo:nil
            repeats:YES];
    }
    return newInstance;
}

-(void)onTick:(NSTimer *)aTimer {
    NSLog(@"Tick");
}
@end

int main() {
    @autoreleasepool {
        MyClass *obj = [[MyClass alloc] init];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}