来自开发人员库的NSTimer

时间:2013-12-02 00:10:25

标签: objective-c uilabel nstimer

我一直在玩开发人员库中的一些代码,但很难理解它的用途。我正在尝试使用我在NSLog中看到的内容更新标签,尽管我似乎可以做的是按下按钮时使用格式化的时间更新标签。我希望用我在NSLog中看到的内容更新标签。我知道可能有一种更简单的方法,但我只是想了解这段代码以及如何使用NSLog中打印的内容更新UILabel?如果你能提供帮助,谢谢你。

这是我的代码:

#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

以下是实施:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{

    NSString *stringFromDate;
    NSDateFormatter *formatter;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    formatter = [[NSDateFormatter alloc]init] ;

}

/************************************************/
/*  Timer methods  */
- (NSDictionary *)userInfo {
    return @{ @"StartDate" : [NSDate date] };
}

- (void)targetMethod:(NSTimer*)theTimer {
    NSDate *startDate = [[theTimer userInfo] objectForKey:@"StartDate"];


    NSLog(@"Timer started on %@", startDate);



        stringFromDate = [formatter stringFromDate:startDate];
        [formatter setDateFormat:@"hh:mm:ss"];
        self.label.text = [NSString stringWithFormat:@"%@",stringFromDate];

}

- (IBAction)startRepeatingTimer:sender {

    // Cancel a preexisting timer.
    [self.repeatingTimer invalidate];

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5
                                                      target:self selector:@selector(targetMethod:)
                                                    userInfo:[self userInfo] repeats:YES];
    self.repeatingTimer = timer;
}



- (IBAction)buttonPressed:(id)sender
{
    [self startRepeatingTimer:sender];


}
@end

1 个答案:

答案 0 :(得分:1)

由于问题是您反复获得相同的日期/时间,因此您需要更改获取当前日期/时间的方式。摆脱计时器上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:。并确保在格式化日期之前设置格式化程序的格式

为什么在标签中每半秒运行一次计时器只显示到最近的秒的时间?