调用 NSTimer 方法
我刚开始在 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;
}
感谢任何能指引我正确方向的事情。
I'm new to working with timers on the iPhone
and would need some support.
I have a method as below that takes the time and update a UILabel
in my userinterface
. I also have an NSTimer
that calls that method once a second (I only show hours and minutes). This works just fine, except for the first second the App is live (as I understand it takes one second before the timer
calls the method).
I would like to call my method from viewDidLoad
, but how can I supply the right arguments? Or is there a better way of doing this?
// 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;
}
Appreciate anything that would point me in the right direction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在你的方法中,你没有使用计时器变量,对吗?那么,为什么只调用
[self updateTime:nil]
。那应该有效In your method, you don't use the timer variable right? So, why just call
[self updateTime:nil]
. That should work还有一种选择......你可以这样做:
One more option ... you can do: