在 Instrument 的帮助下,我发现以下代码段存在内存泄漏。 仪器显示 NSDateFormatter 此处内存泄漏。
- (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;
}
谢谢
更改这些行
NSString *message = [[formatter stringFromDate:d] retain];
delegatObj.selecteddate=message;
通过这些线
NSString *message = [formatter stringFromDate:d];
[message retain];
delegatObj.selecteddate=message;
[message release];
所选日期也是保留类型的属性,因此不要直接对其调用保留。它增加了保留计数。
您不需要保留消息。它将由代表拥有。
试试这个:
- (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];
[formatter setDateFormat:@"MMMM-dd-yyyy"];
NSString *message = [formatter stringFromDate:d];
delegatObj.selecteddate=message;
NSLog(@" selectd %@ ",delegatObj.selecteddate);
[delegatObj getholiday_forcalnder];
[formatter release];
return d;
}