Iphone 获取当前时间并保持更新-目标C

Iphone 获取当前时间并保持更新-目标C,iphone,ios,objective-c,Iphone,Ios,Objective C,我知道如何使用NSDate获取时间并将其显示在UILabel中 我需要显示日期+小时和分钟。 你知道我怎样才能在不忙着等待的情况下保持更新吗 谢谢 您可以使用NSTimer定期获取当前时间 [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; - (void)timerFired:(NSTimer*)theTimer{ /

我知道如何使用NSDate获取时间并将其显示在UILabel中

我需要显示日期+小时和分钟。 你知道我怎样才能在不忙着等待的情况下保持更新吗


谢谢

您可以使用NSTimer定期获取当前时间

[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

- (void)timerFired:(NSTimer*)theTimer{
 //you can update the UILabel here.
}

使用NSTimer更新标签上的时间

- (void)viewDidLoad
 {
  [super viewDidLoad];

   [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
 }



-(void)updateTime
{


NSDate *date= [NSDate date];
NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init]; //for hour and minute

formatter1.dateFormat = @"hh:mm a";// use any format 

clockLabel.text = [formatter1 stringFromDate:date];

[formatter1 release];


}

您可以使用NSTimer,但鉴于上述方法,UILabel不会在触摸事件时更新,因为主线程将忙于跟踪它。您需要将其添加到
mainRunLOOP

    NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabelWithDate) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

-(void)updateLabelWithDate
{
   //Update your Label
}

您可以更改时间间隔(您希望更新的速率)。

如您的评论所述,如果您希望在分钟更改时更改标签。text

你应该这样做:

第一:获取当前时间:

NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
并设置
label.text=CURRENTHOUR_和_YOURMINNUTS

然后在下一分钟刷新标签,如下所示:

首先,您可以在
60秒后检查
[自执行选择器:@selector(refreshLabel)with object:nil afterDelay:(60-dateComponents.minute)]

它会每分钟检查一次,所以有效性比上面的答案要高


refreshLabel
已开票时,这意味着更改的分钟将为我提供当前时间,但我不想一直要求它…这正是我试图避免的。。。就我所知,没有这样的通知。正如我之前所写的,这正是我试图避免的。我想听听每次会议记录改变时都会触发的通知?没有这样的通知。如果您需要定期发生某些事情(如标签的文本更改),则可以使用计时器。当使用
scheduledTimer…
创建计时器时,它已添加到运行循环中。这是不必要的。
performSelector:afterDelay:
的效率并不比计时器高,而且这个解决方案不必要地复杂。@JoshCaswell您没有仔细看到我的答案。他想每分钟刷新一次标签。所以我要求刷新标签,每60秒刷新一次,他们每1秒刷新一次,所以我说我的答案更有效我不理解这种差异,你是对的,但事实上最好以比你实际想要显示的更小的间隔检查时间,因为NSTimer和
性能选择器:afterDelay:
都不能保证在设定的时间准确触发。您也不需要主队列或
NSDateComponents
中的位,而且根本不清楚什么是
CURRENTHOUR\u和\u yourmnuts应该是”JoshCaswell。
NSDateComponents
用于获取小时和分钟(通过
dateComponents.hour
dateComponents.minute
),因为他想显示小时和分钟,我不知道他想要什么格式,所以我使用
CURRENTHOUR\u和\u YOURMINNUTS
。刷新UI(label.text)不能使用主线程?在此之前,您不在后台线程上,应该使用格式化程序进行格式化。
- (void)refreshLabel
{
    //refresh the label.text on the main thread
    dispatch_async(dispatch_get_main_queue(),^{      label.text = CURRENT_HOUR_AND_MINUTES;    });
    // check every 60s
    [self performSelector:@selector(refreshLabel) withObject:nil afterDelay:60];
}