开发者

How to increment an NSDate

开发者 https://www.devze.com 2022-12-18 23:47 出处:网络
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 ge

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:dateCompon开发者_StackOverflowents 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 --


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

精彩评论

暂无评论...
验证码 换一张
取 消