I have followed all the rules of memory management but can someone explain to me why this is causing a double free exception:
- (NSString *)formattedStringWithDecimal:(NSDecimalNumber *)decimalNumber
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0]; //zero deimal spaces
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp]; //round up
return [[formatter stringFromNumber:decimalNumber] autorelease];
}
This is how I am calling it:
//Set the label of the cell formatting the distance from the device
cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@ miles",
selectedAirport.name, [self formattedStringWithDecimal:selectedAirport.milesFromDevice]];
I have subsequently changed it to this which now works - however I still don't know what I did wrong in the first piece of code.
- (NSString *)formattedStringWithDecimal:(NSDecimalNumber *)decimalNumber
{
NSNumberFormatter *formatter = [[NSNumberFormatter al开发者_如何学JAVAloc] init];
[formatter setMaximumFractionDigits:0]; //zero deimal spaces
[formatter setRoundingMode: NSNumberFormatterRoundHalfUp]; //round up
NSString *result = [NSString stringWithString:[formatter stringFromNumber:decimalNumber]];
[formatter release];
return result;
}
The method stringFromNumber:
returns an autoreleased string. In the first method, that returned string is being autoreleased a second time. Also, in the first method, formatter
was never being released. In short, the string was being released an extra time and the formatter was leaking.
The second method looks much better. Perhaps there was some confusion between releasing formatter
and releasing the string returned by stringFromNumber:
. The line:
return [[formatter stringFromNumber:decimalNumber] autorelease];
sends the autorelease
message to the string produced by [formatter stringFromNumber:decimalNumber]
, not to the formatter itself.
精彩评论