0

テキストを出力する必要があるコード行の直前にある NSLog が正しい値を返しているため、この問題はちょっと奇妙です。

コードは次のとおりです。

-(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 の行です。

ご助力いただきありがとうございます!

乾杯、マット

4

1 に答える 1

1

ニブを使用した場合

ペン先がロードされ、すべての接続が確立されると... (リソース プログラミング ガイドより)

set OutletName:形式のメソッドを探し、そのようなメソッドが存在する場合はそれを呼び出します

したがって、nib はロードsetCurrentDate:され、アーカイブUILabelされていないものをパラメーターとして渡します。

メソッドでは、メソッドに渡されたローカルUILabel参照を使用して構成します

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

this への参照を ivar に実際に保存することは決してないUILabelため、技術的にはラベルを漏らし、ivar を設定していないため、currentDate初期化されnilます。これは、不適切な実装でセッターをオーバーライドする危険性があります。

メソッドのある時点で、ivar を渡された変数に設定する必要があります。通常のセッターはこんな感じ

- (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];

実装は次のようになります。

- (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]];
}
于 2012-01-02T21:39:38.503 に答える