iphone - 使用 NTimer 更新 NSDateFormatter

标签 iphone objective-c ios xcode ipad

我创建了一个显示时间日期格式化程序的自定义类,我需要一个类似计时器的方法来更新秒数,所以这是我的代码:

自定义类.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/

相关文章:

ios - Firebase 远程配置崩溃( objective-c iOS)

ios - Swift 3 Horizo​​ntal Multiple UIScrollView - 不同的速度

ios - swift :键盘行为。为什么 'touchesBegan'使用scrollView时不最小化键盘?

iphone - 如何在单击 MPMoviePlayerController 中的“完成”按钮时添加自定义功能

iphone - 用于 iPhone 游戏开发的 Cocos2d 中的图层与场景

objective-c - 当客户端断开连接时如何获取 NSNetService 通知?

ios - 创建重复事件而不在 iOS 的日历中显示这些事件

iphone - NSLocale 设置首选语言

ios - Swift - 将两个数组元素添加到tableView中的detailTextLabel

iphone - 像在 iPhone SMS 应用程序中一样实现添加联系人