2012-01-02 94 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