我创建了一个显示时间日期格式化程序的自定义类,我需要一个类似计时器的方法来更新秒数,所以这是我的代码:
自定义类.m
- (NSString *) showLocaleTime {
NSDateFormatter *timeFormater = [[NSDateFormatter alloc] init];
timeFormater = [setDateFormat:@"HH:mm:ss "];
NSString *currDay = [timeFormater stringFromDate:[NSDate date]];
currDay = [NSString stringWithFormat:@"%@",currDay];
[timeFormater release];
return timer;
}
- (void) updateLocaleTime {
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(showLocaleTime) userInfo:nil repeats:YES];
}
viewController.m:
CustomClass *time = [[CustomClass alloc]init];
label.text = [time showLocaleTime];
[time updateLocaleTime];
但问题是 updateLocaleTime
没有调用更新秒数!我错过了什么吗?
谢谢
最佳答案
无需在 CustomClass
中调用 updateLocaleTime
,只需在 View Controller 本身中启动计时器即可。
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLocaleTime) userInfo:nil repeats:YES];
将updateLocaleTime
方法添加到viewController
- (void) updateLocaleTime {
CustomClass *time = [[CustomClass alloc]init];
label.text = [time showLocaleTime];
[time release];
}
但这里我们每 0.5 秒一次又一次地分配和释放 CustomClass
。相反,您在 .h 文件中将其声明为类成员,并在 viewDidLoad
中分配它。
所以不需要在updateLocaleTime
方法中分配。同时在 viewDidUnload
方法中释放该时间
。
关于iphone - 使用 NTimer 更新 NSDateFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8834855/