我想在时间格式为hh:mm:ss的标签上显示当前时间

时间:2016-03-09 13:01:04

标签: ios objective-c nsdate nsdateformatter

当前时间格式应该像hh:mm:ss和秒应该运行,秒不应该停止计数,它应该继续运行让我告诉你我正在写的代码。

-(void)timeNotify
{
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:currDate];

_timeLbl.text=dateString;

}

并且在视图中加载我正在调用此

-(void)viewDidLoad
{
  [self timeNotify];
}

3 个答案:

答案 0 :(得分:4)

您应该使用NSTimer

- (void)viewDidLoad
{
  [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self
                                   selector:@selector(timeNotify)
                                   userInfo:nil
                                    repeats:YES];
}

- (void) timeNotify
{
    NSDate *currentTime = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm:ss"];
    NSString *resultString = [dateFormatter stringFromDate: currentTime];
    _timeLbl.text = resultString;
}

答案 1 :(得分:-1)

如果您希望定期更新时间,则应使用NSTimer

NSTimer* timer =       [NSTimer scheduledTimerWithTimeInterval:1
                                   target:self
                                 selector:@selector(timeNotify)
                                 userInfo:nil
                                  repeats:YES]; 

当视图消失时,请记住将timer设置为nil,因为计时器会保持对ViewController的引用,因此如果您不销毁它将导致内存泄漏

答案 2 :(得分:-2)

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSLog(@"User's current time in their preference format:%@",currentTime);