2011-03-29 49 views
0

我一直在试图弄清楚如何设置一个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类中带有回调函数?

谢谢你的时间和耐心。

回答

2

根本不需要处理运行循环。

这条线:

NSTimer *timmeh = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(printCurrentTime) userInfo:nil repeats:YES]; 

将创建一个定时器,其附加到你当前线程的run loop。您根本不需要拨打[NSRunLoop addTimer:forMode:] - 您可以删除该行。

PS你当然不需要去NSThreads!


编辑关于你的评论:

你需要让你的TimeStuff类的实例的时间。如果这就是你的printCurrentTime方法是使用。即

@interface MyViewController : UIViewcontroller { 
    TimeStuff *timeStuff 
} 

,并在您的viewDidLoad方法:

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    ... 

    // Create our timestuff if we don't have one already 
    if (nil == timeStuff) 
     timeStuff = [[TimeStuff alloc] init]; 

    // Start the timer 
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:timeStuff selector:@selector(printCurrentTime) userInfo:nil repeats:YES]; 

,不要忘了的dealloc

- (void)dealloc { 
    [timeStuff release]; 
    ... 
    [super dealloc]; 
} 

在timeStuff传递为目标的计时器告诉它到哪里寻找的printCurrentTime方法!

希望帮助,

PS所有行@class TimeStuff所做的就是告诉编译器有一个叫TimeStuff类。它不知道你想用它作为你的计时器的选择器!

+0

嗨,谢谢你的指导。我按照建议实现,但我得到了“无法识别的选择器发送到实例”和一个SIGABRT。选择器的范围是什么?文件级?我在另一个类文件(TimeStuff.m)中实现了实际的函数printCurrentTime,尽管包含'@class TimeStuff'在ViewController类文件(其中,NSTimer是在哪里 - 在viewDidLoad:方法),我仍然得到这个错误。任何想法? - 谢谢 – swisscheese 2011-03-30 15:20:56

+0

选择器的作用域是'target'参数!如果你传递'self'作为目标,那么选择器必须是当前类的一个方法。您应该传入TimeStuff类的实例作为目标。 – deanWombourne 2011-03-30 15:35:49

+0

查看我编辑的问题,以更清晰地回答您的评论 - 我总是比较喜欢一段文字的例子! – deanWombourne 2011-03-30 15:48:24