Should I copy and auto-update this line?
When going with the debugger through this, dfString is invalid after [df release]
- (NSString*)dateFormatStringWithLocale:(NSLocale*)locale {
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterShortStyle];
[df setTimeStyle:NSDateFormatterShortStyle];
[df setLocale:locale];
NSString *dfString = [df dateFormat]; // dfString now contains nice date format
[df release]; // seems to also kill dfString ???
return dfString; // dfString is invalid here
}
Think about it: dfString is an object just like any other. I am asking for a string from df using [df dateFormat]. However, I don't own this line, so I don't need to release it. But I have df, so I release it. Now let's suppose the string I get from [df dateFormat] is some ivar df and gets -release'd in -dealloc df. Then that damn line disappeared. But when I call - go to this dfString which is just a pointer to a string owned by df then damn df will not be released. So what should I do? copy the line and auto update it?
I would do, as you say, make an auto-implemented string, or like this:
NSString *dfString = [NSString stringWithString: [df dateFormat]];
or like this:
NSString *dfString = [[[df dateFormat] copy] autorelease];
I prefer the former, but please correct me if there is anything wrong with it.
source to share
It's a question of ownership. The formatter owns the string you are looking at. So the line dies after the formatter leaves. You must somehow claim ownership of this string using a copy or keep.
It actually depends on how the accessor is implemented. Both implementations below are absolutely correct:
- (NSString*) dateFormat
{
return dateFormat;
}
- (NSString*) dateFormat
{
return [[dateFormat copy] autorelease];
}
In fact, the first one is only appropriate if you can be sure that the DateFormat is immutable NSString
. That is, if you made a copy of whatever string you passed in. Otherwise, the caller might be tempted to make changes to their own string.
source to share
Try the following:
NSString *dfString = [[df dateFormat] retain];
Since dfString is probably an instance variable of dfString, it is freed when df is freed. Try to just keep dfString. In dealloc, its keepCount is lowered by one, but it will not be released completely since you now have ownership. See if this helps.
source to share