I am trying to clean up memory leaks and other issues in an existing iPhone app. I am a little new to Objective C, but have some good programming fundamentals and a general understanding of the memory management that is required when dev’ing iphone apps. My question is about the following method below.
-(NSDate *)formatDate:(id)value{
NSLog(@"eja: DetailViewController/ formatDate()");
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.S"];
[dateFormatter release];
return [dateFormatter dateFromString:value];
}
It is returning an error reading “Referenced-counted object is use after it is released“. I see that dateFormatter is being freed before it is returned/used. The issue is of course that if you put the release after the return statement you get a ‘Potential leak of an object’ error associated with dateFormatter var declaration.
I also tried “autorelease”
return [[dateFormatter dateFromString:value] autorelease];
But I then get the error ‘Object sent – autorelease too many times‘.
Any words of advice on how to write this properly so the variables are properly managed?
Replace
with
and it should work!