2012-01-12 60 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