I know this is fairly fundamental stuff.
I have a class with a function that returns the name of the month; I’m not sure how to release a value that I want to return to prevent leaks.
In the class this value is declared:
static NSDateFormatter *formatter = nil;
if (formatter == nil) {
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM yyyy"];
}
Things happen, and then:
if([exampleDate isEqualToDate:
[[self creationDate] laterDate:exampleDate]])
{ //earlierDate returns the earlier date
return(@"Examples");
}else{
return([formatter stringFromDate:[self creationDate]]);
}
I’ve tried using autorelease but I’m using it incorrectly because I get a crash when I try to release it. I’ve also tried assigning the return value to a string, but I have the same crashing problems. Sorry for asking a question that is so fundamental, but I’d appreciate knowing how to release this properly, while still returning the value – and understanding how it works.
there are no leaks in the return part. Since
stringFromDate:is notcopy,mutableCopy,retain,allocornewit returns already an autoreleased object.Your
NSDateFormatterwill leak when the class is deallocated. If you don’t want it to leak you should create a@propertyfor it and release it in dealloc.Local static objects will always leak.
I would not use such objects outside of singletons. Each time you create one of your classes you will leak an NSDateFormatter. Using
@propertyis better in almost every case.I’ve seen hacks like this but in my opinion they solve a problem you shouldn’t have in the first place: