【发布时间】:2011-03-29 11:59:48
【问题描述】:
我一直在试图弄清楚如何设置 NSTimer 以允许我在视图中的 UILabel 中打印当前时间,并让它每秒更新一次(不需要更精细的分辨率 - 只需一个简单的时钟)。
起初,我没有使用 NSRunLoop,但如果我尝试包含一个,则执行只会在循环内“旋转”,从而阻止进一步的执行。我已经在下面发布了我的代码。
-(id) printCurrentTime {
now = [NSDate date];
dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeStyle:NSDateFormatterMediumStyle];
NSString *nowstr = [dateFormat stringFromDate:now];
[dateFormat release];
NSLog(@"Current time is: %@",nowstr);
return nowstr;
}
在 ViewController 源文件中,我按如下方式执行:
TimeStuff *T = [[TimeStuff alloc] init];
NSString *thetime = [T printCurrentTime];
[timelabel setText:thetime];
[T release];
[self.view addSubview:timelabel];
NSTimer *timmeh = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(printCurrentTime) userInfo:nil repeats:YES];
[[[NSRunLoop currentRunLoop] addTimer:timmeh forMode:NSDefaultRunLoopMode] run];
“TimeStuff”类实际上是一个空类,除了 printCurrentTime 函数。
问题:
1) 我应该在 AppDelegate 类中包含 RunLoop 吗?我无法想象这一切应该如何结合在一起,例如 - 实现基于 Timer 的循环以最多秒更新文本标签的步骤是什么。好难过。
2) 如果我应该使用 NSThread,那也应该在它自己的类/Delegate 类中。
3) ViewController 类是否完全超出了循环/计时器的范围,只是“眼睛糖果”类,带有对 Delegate 类中函数的回调?
感谢您的时间和耐心。
【问题讨论】:
标签: iphone objective-c