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

40P*_*lot 1 objective-c nstimer ios

我有:

- (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]];
    });
}
Run Code Online (Sandbox Code Playgroud)

但没有什么可以被称为

Mic*_*ann 7

你正在调用错误的选择器.您的" setCurrentTime"实现不接受任何参数(例如,要正确地发送消息或调用,您应该使用" selector:@selector(setCurrentTime)".

现在,如果你查看Apple的文档[NSTimer scheduledTimerWitTimeInterval: target: selector: userInfo: repeats:],Apple说你的方法应该有这个签名:

- (void)setCurrentTime: (NSTimer *) timer
Run Code Online (Sandbox Code Playgroud)

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

-(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]];
    });
}
Run Code Online (Sandbox Code Playgroud)

并像这样调用:

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