我一直在试图弄清楚如何设置一个NSTimer,让我能够在视图内的UILabel中打印当前时间,并且每秒更新一次(不需要更精细的分辨率 - 只是一个简单的时钟)。首先,我没有使用NSRunLoop,但是如果我尝试并包含一个,执行只是在循环内部“旋转”,阻止了进一步的执行。我已经在下面发布了我的代码。NSRunLoop/NSTimer属于哪个源文件?
-(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;
}
而视图控制器源文件中,我执行按:
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)我应该包括RunLoop在AppDelegate类?我无法想象如何将所有这些应该挂在一起,例如 - 基于定时器实现循环的步骤是什么,以便用最新的时间更新文本标签。很难过。
2)如果我应该使用NSThread,应该也是它自己的类/委托类。
3)ViewController类是否完全超出了循环/定时器的范围,并且只是“眼睛糖果”类,在Delegate类中带有回调函数?
谢谢你的时间和耐心。
嗨,谢谢你的指导。我按照建议实现,但我得到了“无法识别的选择器发送到实例”和一个SIGABRT。选择器的范围是什么?文件级?我在另一个类文件(TimeStuff.m)中实现了实际的函数printCurrentTime,尽管包含'@class TimeStuff'在ViewController类文件(其中,NSTimer是在哪里 - 在viewDidLoad:方法),我仍然得到这个错误。任何想法? - 谢谢 – swisscheese 2011-03-30 15:20:56
选择器的作用域是'target'参数!如果你传递'self'作为目标,那么选择器必须是当前类的一个方法。您应该传入TimeStuff类的实例作为目标。 – deanWombourne 2011-03-30 15:35:49
查看我编辑的问题,以更清晰地回答您的评论 - 我总是比较喜欢一段文字的例子! – deanWombourne 2011-03-30 15:48:24