过度释放NSDecimalNumber

时间:2010-11-26 21:35:26

标签: objective-c memory-management nsdecimalnumber

我的应用告诉我,我在下面过度释放了NSDecimalNumber tempDouble:

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];

我认为问题就在于此问题:

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

但我不确定为什么。我应该在分配后添加“分配,复制或保留”属性吗?当我摆脱下面的'发布'声明时,代码工作正常。

谢谢,

1 个答案:

答案 0 :(得分:0)

问题确实在这一行:

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

你在这里做的是用一个新值(自动释放)替换tempDouble中的前一个值(保留计数为1)。

这是正确的方法:

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

然后从方法的末尾删除[tempDouble release]