質問

私は1ヶ月NSDateインスタンス変数をインクリメントするメソッドを実装しようとしています。私はこれで、メモリ管理の問題を抱えています。 (私はMallocScribbleとNSZombieEnabledを使用して、メッセージを取得しています: - [CFDateコピー]:割り当て解除インスタンス0x3d9dfa0に送信されたメッセージ)

私の質問は、まで来る:日付をインクリメントするための最良の方法は何ですか?ここに私のコードは次のとおりです。

NSDate *displayedMonthYear;
....

-(IBAction) nextMonth:(id)sender {

    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setMonth:1];
    NSDate *prevDate = [displayedMonthYear copy];
    [displayedMonthYear release];
    displayedMonthYear = [calendar dateByAddingComponents:dateComponents toDate:prevDate options:0];
    [prevDate release];
    [dateComponents release];
    [calendar release];
}

もともと私はprevDateコピーしてビットをしていなかったが、のようなものをやっていた。

displayedMonthYear = [calendar dateByAddingComponents:dateComponents toDate:displayedMonthYear options:0];

しかし、私はそのアプローチは、メモリリークが発生することを心配していました。だから私は、これは、日付の問題よりも、メモリ管理の問題の詳細ですが、任意のヘルプは素晴らしいことだと思います -

役に立ちましたか?

解決

あなたはretainに割り当てられた値をdisplayedMonthYearする必要があります。

copyを使用する必要もありません。それを行うための方法はたくさんあります。ここでもう一つの例があります:

NSDate* newDate = [calendar dateByAddingComponents:dateComponents displayedMonthYear options:0];
[displayedMonthYear release];
displayedMonthYear = [newDate retain];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top