Objective c 来自开发人员库的NSTimer
我一直在玩弄开发人员库中的一些代码,但很难理解它到底是怎么回事。我正在尝试用NSLog中打印的内容更新标签,尽管我似乎能做的只是在按下按钮时用格式化的时间更新标签。我想用我在NSLog中看到的内容更新标签。我知道可能有一种更简单的方法,但我只是想了解这段代码,以及如何用NSLog中打印的内容更新UILabel?如果你能帮忙,谢谢你 这是我的密码:Objective c 来自开发人员库的NSTimer,objective-c,uilabel,nstimer,Objective C,Uilabel,Nstimer,我一直在玩弄开发人员库中的一些代码,但很难理解它到底是怎么回事。我正在尝试用NSLog中打印的内容更新标签,尽管我似乎能做的只是在按下按钮时用格式化的时间更新标签。我想用我在NSLog中看到的内容更新标签。我知道可能有一种更简单的方法,但我只是想了解这段代码,以及如何用NSLog中打印的内容更新UILabel?如果你能帮忙,谢谢你 这是我的密码: #import <UIKit/UIKit.h> @interface ViewController : UIViewController
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak) NSTimer *repeatingTimer;
@property NSUInteger timerCount;
@property NSString *stringFromDate;
@property (weak, nonatomic) IBOutlet UILabel *label;
- (IBAction)startRepeatingTimer:sender;
- (IBAction)buttonPressed:(id)sender;
- (void)targetMethod:(NSTimer*)theTimer;
- (NSDictionary *)userInfo;
@end
由于问题是您一次又一次地获得相同的日期/时间,因此需要更改获取当前日期/时间的方式。不要在计时器上使用
userInfo
。这就是问题的原因
- (void)targetMethod:(NSTimer*)theTimer {
NSDate *date = [NSDate date];
NSLog(@"Current date: %@", date);
[formatter setDateFormat:@"hh:mm:ss"];
stringFromDate = [formatter stringFromDate:date];
self.label.text = stringFromDate;
}
- (IBAction)startRepeatingTimer:sender {
// Cancel a preexisting timer.
[self.repeatingTimer invalidate];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
self.repeatingTimer = timer;
}
另外,不要不必要地使用stringWithFormat:
。并确保在格式化日期之前设置格式化程序的格式
为什么标签上的计时器每半秒运行一次,只显示最接近秒的时间?您唯一的问题是记录的日期与标签上的日期格式不同吗?我希望标签不断更新。尽管它只在按下按钮时更新。格式不困扰我。太好了,我做到了!我将scheduledTimerWithTimeInterval中的值更改为1,在显示屏上看起来更好。它来自开发者库,我只是想学习如何实现它,不需要字典。
- (void)targetMethod:(NSTimer*)theTimer {
NSDate *date = [NSDate date];
NSLog(@"Current date: %@", date);
[formatter setDateFormat:@"hh:mm:ss"];
stringFromDate = [formatter stringFromDate:date];
self.label.text = stringFromDate;
}
- (IBAction)startRepeatingTimer:sender {
// Cancel a preexisting timer.
[self.repeatingTimer invalidate];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self selector:@selector(targetMethod:)
userInfo:nil
repeats:YES];
self.repeatingTimer = timer;
}