2012-01-02 91 views
0

ok,所以這個問題有點奇怪,因爲NSLog我有權在應該打印出文本的代碼行前面返回正確的值。標籤沒有在setter中更新

下面的代碼:

-(void)setCurrentDate:(UILabel *)currentDate 
{ 

NSInteger onDay = 1; //because if it's today, you are on day one, not zero... no such thing as a day zero 

//get the nubmer of days left 
if([[NSUserDefaults standardUserDefaults] objectForKey:@"StartDate"]){ //if there is something at the userdefaults 
    onDay = [self daysToDate:[NSDate date]]; 
}//otherwise, onDay will just be one 

self.theCurrentNumberOfDaysSinceStart = onDay; 

NSLog(@"On day: %d", onDay); //this is returning the correct values.... 

//print it out on the label 
[currentDate setText:[NSString stringWithFormat:@"On day: %d", onDay]];//echoes out the current day number 

} 

所以,當應用程序第一次啓動,一切都很好。標籤更新和一切。當我點擊一個基本上抓住新日期的按鈕時,問題就出現了。在這個過程中,運行此:

//need to reload the "on day" label now 
    [self setCurrentDate:self.currentDate]; 
    //and the "days left" label 
    [self setDaysLeft:self.daysLeft]; 

同樣,我想這應該都是正確的,因爲NSLog的是返回正確的東西。我認爲問題出在我顯示的第一個代碼塊中的最後一行...與setText一致。

感謝您的幫助!

歡呼聲, 馬特

+1

你能否證實'currentDate'不是'nil'打電話時'的setText:' – 2012-01-02 20:52:53

+0

還有什麼是你想達到這個'[自我setCurrentDate:self.currentDate]'?我認爲只需要調用一個方法來設置文本值不會將相同的對象重新分配給自己,並且副作用可以設置日期,這會更有意義。 – 2012-01-02 20:58:36

+0

是的...它是NULL ...但1)我不明白爲什麼,因爲它不是標籤本身? 2)它第一次工作,爲什麼不在其他時間呢? =/ – 2012-01-02 21:24:17

回答

1

如果您使用的筆尖

當筆尖負荷,並建立所有它的連接它的...(從​​)

查找形式set的方法方法名稱:並且如果存在這樣的方法則調用它

因此,筆尖會加載並調用setCurrentDate:在未歸檔UILabel傳遞作爲參數

在你的方法配置使用本地引用傳遞到方法的UILabel

[currentDate setText:[NSString stringWithFormat:@"On day: %d", onDay]]; 

您在沒有任何一點實際上將這個UILabel的參考存儲在ivar中,所以在技術上你已經泄露了該標籤,並且因爲你沒有設置ivar currentDate它將被初始化爲nil。這是覆蓋一個錯誤實現的setter的危險。

在你的方法的某個點,你應該設置你的伊娃到傳入的變量。一個正常的setter方法應該是這樣的

- (void)setCurrentDate:(UILabel *)currentDate; 
{ 
    if (_currentDate != currentDate) { 
     [_currentDate release]; 
     _currentDate = [currentDate retain]; 
    } 
} 

在你的榜樣,我不會擔心這一點在所有我反而改變這種

//need to reload the "on day" label now 
[self setCurrentDate:self.currentDate]; 

喜歡的東西

[self updateCurrentDate]; 

執行看起來如此mething像:

- (void)updateCurrentDate; 
{ 
    NSInteger onDay = 1; 

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"StartDate"]) { 
     onDay = [self daysToDate:[NSDate date]]; 
    } 

    self.theCurrentNumberOfDaysSinceStart = onDay; 

    [self.currentDate setText:[NSString stringWithFormat:@"On day: %d", onDay]]; 
} 
+0

是的,然後做[self updateCurrentDate];在viewWillAppear。已經這樣做了;)我只是想弄清楚爲什麼setter沒有這樣做,但現在它是有道理的。謝謝! – 2012-01-02 21:51:54