调用NSTimer方法

5
我对在iPhone上使用定时器不熟悉,需要一些支持。
我有一个方法,它接受时间并更新我的用户界面中的UILabel。我还有一个NSTimer,每秒调用该方法(我只显示小时和分钟)。这很好用,除了应用程序启动的第一秒钟之外(据我所知,需要一秒钟才能调用计时器方法)。
我想从viewDidLoad中调用我的方法,但是如何提供正确的参数?或者有更好的方法吗?
// Timer for updating time
[NSTimer scheduledTimerWithTimeInterval:1.0f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil 
                                repeats:YES];   


-(void)updateTime: (NSTimer *) timer {

    currentTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *currentTimeString = [dateFormatter stringFromDate:currentTime];
    [dateFormatter release];

    timeLabel.text =  currentTimeString;
}

感谢任何能指引我正确方向的帮助。
2个回答

2

还有一种选择...你可以这样做:

[NSTimer scheduledTimerWithTimeInterval:0.01f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil  
                                repeats:NO];    

[NSTimer scheduledTimerWithTimeInterval:1.0f 
                                 target:self 
                               selector:@selector(updateTime:) 
                               userInfo:nil 
                                repeats: YES];

谢谢 Horace。我想我会去尝试 vodkhangs 的解决方案。 - Structurer

2
在你的方法中,你没有正确使用计时器变量吗?那么,为什么不只调用[self updateTime:nil]。这应该可以工作。

是的,你说得对。这是一个简单而整洁的解决方案。已经测试过了,运行良好。谢谢!似乎还有一个使用“fire”触发计时器事件的解决方案,但我还没有时间测试它。 - Structurer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接