iphoneobjective-cnsdateformatter

NSDateFormatter Memory leaks


With the help of Instrument I found that the following section of the code leaking memory. Instrument saying NSDateFormatter leaking memory here.

- (NSDate*) dateSelected{
if(selectedDay < 1 || selectedPortion != 1) return nil;

TKDateInformation info = [monthDate dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
info.hour = 0;
info.minute = 0;
info.second = 0;
info.day = selectedDay;
NSDate *d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];


HolidayAppDelegate *delegatObj = (HolidayAppDelegate *)[UIApplication sharedApplication].delegate;

NSDateFormatter  *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MMMM-dd-yyyy"];

    // below line getting leak
NSString *message = [[formatter stringFromDate:d] retain];
delegatObj.selecteddate=message;
NSLog(@" selectd %@ ",delegatObj.selecteddate);
[delegatObj getholiday_forcalnder];

return d;

}

Thanks


Solution

  • change these lines

    NSString *message = [[formatter stringFromDate:d] retain];
    delegatObj.selecteddate=message;
    

    by these lines

     NSString *message = [formatter stringFromDate:d];
      [message retain];
    delegatObj.selecteddate=message;
    [message release];
    

    also selected date is property which is of type retain so don't call directy retain on it. It increases the retain count.