iOS NSTimer没有调用选择器 - 没有触发

时间:2013-10-07 05:43:01

标签: ios objective-c nstimer

我有:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self setNeedsStatusBarAppearanceUpdate];
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(setCurrentTime:)  userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    [timer fire];

}
-(void)setCurrentTime{
    NSLog(@"TEST");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDate *currentDate = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [currentTime setText:[dateFormatter stringFromDate:currentDate]];
    });
}

但没有人被召唤。

1 个答案:

答案 0 :(得分:7)

您正在调用错误的选择器。您的“setCurrentTime”实施不会采用任何参数(例如,要正确发送消息或调用,您应使用“selector:@selector(setCurrentTime)”。

现在,如果你看一下Apple's documentation for [NSTimer scheduledTimerWitTimeInterval: target: selector: userInfo: repeats:],Apple说你的方法应该有这个签名:

- (void)setCurrentTime: (NSTimer *) timer

这意味着你的功能看起来像这样:

-(void)setCurrentTime: (NSTimer *) timer
{
    NSLog(@"TEST");
    dispatch_async(dispatch_get_main_queue(), ^{
        NSDate *currentDate = [[NSDate alloc] init];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"HH:mm"];
        [currentTime setText:[dateFormatter stringFromDate:currentDate]];
    });
}

并像这样调用:

NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.25 
                   target:self 
                 selector:@selector(setCurrentTime:)  
                 userInfo:nil 
                  repeats:YES];