Search code examples
objective-cmemory-managementnsdecimalnumber

Over-releasing an NSDecimalNumber


My app is telling me that I'm over-releasing the NSDecimalNumber tempDouble below:

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
        [currencyFormatter setLocale:[NSLocale currentLocale]];
        [currencyFormatter setGeneratesDecimalNumbers:TRUE];
        [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

        // Here is the key: use the maximum fractional digits of the currency as the scale
        int currencyScale = [currencyFormatter maximumFractionDigits];

        NSDecimalNumber* tempDouble = [[NSDecimalNumber alloc] initWithString:self.tempStore];


        NSDecimalNumber* numTen = [[NSDecimalNumber alloc] initWithInt:10];

        tempDouble = [tempDouble decimalNumberByDividingBy:[numTen decimalNumberByRaisingToPower:currencyScale]];

        [numTen release];


        [textField setText:[currencyFormatter stringFromNumber:tempDouble]];

        [currencyFormatter release];
        [tempDouble release];

I'm thinking that the problem line is this one:

tempDouble = [tempDouble decimalNumberByDividingBy:[numTen decimalNumberByRaisingToPower:currencyScale]];

But I'm not sure why. Should I be adding an 'assign, copy or retain' attribute after the assignment? When I get rid of the 'release' statement below, the code works fine.

Thanks,

G


Solution

  • The problem is indeed in this line:

    tempDouble = [tempDouble decimalNumberByDividingBy:[numTen decimalNumberByRaisingToPower:currencyScale]];
    

    What you're doing here is replacing the previous value in tempDouble (which has a retain count of 1) with a new value (which is autoreleased).

    Here's the correct way to do it:

    NSDecimalNumber* tempDouble = [[[NSDecimalNumber alloc] initWithString:self.tempStore] autorelease];
    

    And then delete the [tempDouble release] from the end of the method.