views:

258

answers:

1

I'm trying to implement a method that will increment an NSDate instance variable by one month. I'm having memory management problems with this. (I'm using MallocScribble and NSZombieEnabled, and getting the message: -[CFDate copy]: message sent to deallocated instance 0x3d9dfa0)

My question comes down to: what's the best way to increment a date? Here is my code:

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

Originally I wasn't doing the bit with the prevDate copy, but was doing something like:

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

However, I was concerned that that approach would leak memory. So I guess this is more of a memory management issue than a date issue, but any help would be great --

A: 

You need to retain the value assigned to displayedMonthYear.

There's also no need to use copy. There's lots of ways to do it; here's another example:

NSDate* newDate = [calendar dateByAddingComponents:dateComponents displayedMonthYear options:0];
[displayedMonthYear release];
displayedMonthYear = [newDate retain];
Darren
That worked -- thanks for the help.
SeanG