2012-01-12 62 views
0

我创建了一个自定义的类,它显示时间日期格式,我需要像法的定时器来更新秒,所以这里是我的代码:更新NSDateFormatter用的NSTimer

CustomClass.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不叫更新秒!我错过了什么吗? 谢谢

回答

1

而不是在CustomClass调用updateLocaleTime,只需启动视图控制器本身的计时器。

[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]; 
} 

但在这里,我们分配一次又一次释放CustomClass为每0.5秒。相反,你可以在.h文件中声明它为类成员,并在viewDidLoad中分配它。

所以没有必要在updateLocaleTime方法中分配。也可以在viewDidUnload方法中释放time

+0

有没有办法像我说的那样调用这个方法? :-s我需要它,它的公共API给我的朋友我需要它非常简单 – 2012-01-12 13:03:28

+1

正如爱因斯坦所说,一切都应该尽可能简单,但并不简单。 – 2012-01-12 13:29:15

+0

谢谢,但我收到了'SIGABRT' !!? – 2012-01-12 13:52:54

0

在计算新时间后,您在哪里更新标签文本? (你计算新的时间,但它落在地板上。)

例如,将label.text = timer;添加到您的showLocalTime方法,并跳过返回timer

+0

in'viewDidLoad' – 2012-01-12 12:23:31

+0

没有什么变化! – 2012-01-12 12:27:32

+0

更新文本值后,您可能需要执行'setNeedsDisplay'。 – 2012-01-12 13:26:42