Memory leak when using NSDateFormatter

I have seen many questions / answers about memory leaks in NSDateFormatter, but no one helps me determine what causes a memory leak in my application. Here is my code:

- (id)init { if ((self = [super init])) { items = [[NSMutableArray alloc] init]; events = [[NSMutableArray alloc] init]; buffer = [[NSMutableData alloc] init]; format = [[NSDateFormatter alloc] init]; lastFromDate = @""; } return self; } - (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate { [format setTimeZone:[NSTimeZone systemTimeZone]]; [format setDateFormat:@"MM/dd/yyyy"]; NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]]; NSString *stringToDate = [NSString stringWithString:[format stringFromDate:toDate]]; NSLog(@"From date: %@, To date: %@", stringFromDate, stringToDate); [self didDatesChange:stringFromDate]; if (dataReady) { [callback loadedDataSource:self]; return; } callback = delegate; [self retrieveEventData:stringFromDate to:stringToDate]; } - (void)dealloc { [items release]; [events release]; [buffer release]; [lastFromDate release]; [format release]; [super dealloc]; } 

When I run Profile → Leaks, I get a memory leak every time a function is called on a line

 NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]]; 

Can someone explain what could be? thanks mike

+6
source share
2 answers

FYI you can change this:

  NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]]; 

:

  NSString *stringFromDate = [format stringFromDate:fromDate]; 

stringWithString should return an autoreleased NSString, although I don't think this is the source of your leak. There seems to be no leak in your code.

+2
source

you just use the following method to get a string from the date it worked correctly ......

 -(NSString *)StringFromDate:(NSDate *)DateLocal{ NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"MM/dd/yyyy"]; NSString *dateString = [dateFormat stringFromDate:DateLocal]; NSLog(@"Date is HERE =====>> %@",dateString); return dateString; } 

after you want to get the date string, just use as below.

 NSString *stringFromDate = [self stringFromDate:fromDate]]; [stringfromdate retain]; NSString *stringToDate = [self stringFromDate:toDate]]; [stringTodate retain]; 

and up - (NSString *) StringFromDate: (NSDate *) The DateLocal method must be defined in the viewcontroller.m file .... Its work is fine ....

+2
source

Source: https://habr.com/ru/post/913756/


All Articles