问题在循环中添加到NSMutableArray

时间:2011-01-21 07:40:14

标签: cocoa memory-management nsarray nsnumber sigabrt

我不确定这个循环究竟是什么问题,但每次运行时我都会一直收到SIGABRT。根据日志,问题是当我尝试将NSNumber添加到循环结束附近的NSMutable数组时。显然我犯了一个基本错误,但我不确定问题是什么。

NSArray *toArray = [ourDictionary objectForKey:toString];
NSMutableArray *allValuesMArray = [[NSMutableArray alloc] init];
while (done == NO)
{
    if (i == 10)
        done = YES;
           /* 
            *The job here is to multiply these three numbers together and store the 
            *product in the mutable array. It tells me NSObject did not recognize selector
            *and then crashes.
            *original and multiplyFrom are always the same value, and multiplyTo is updated
            *from an array I made above from a p-list.
            *I'm hoping I didn't make a ton of rookie mistakes here, but I'm new to dealing with
            *NSMutableArray and such.
            */

    NSNumber *original = [NSNumber numberWithDouble:convertThis];
    NSNumber *multiplyFrom = [NSNumber numberWithDouble:multiply];
    NSNumber *multiplyTo = [NSNumber numberWithDouble:[[toArray objectAtIndex:i] doubleValue]];
    NSNumber *product = [[NSNumber alloc] init];

    product = [NSNumber numberWithDouble:([original doubleValue] * 
                                          [multiplyFrom doubleValue] *
                                          [multiplyTo doubleValue])];

    [allValuesMArray addObject:product];
            //This line ^^^ causes crash
    i++;
}
NSArray *returnThisArray = allValuesMArray;
[allValuesMArray autorelease];
return returnThisArray;

4 个答案:

答案 0 :(得分:0)

您正在发布allValuesMArray:[allValuesMArray release];

由于此时保留计数为0,因此将立即释放该数组。

尝试使用[allValuesMArray autorelease]。这将在将来释放数组,使调用方法有机会使用未发布的数组或保留数组供以后使用。

此外,您可以在将产品添加到阵列之前检查产品是否为零。

你的内存泄漏了。

product = [[NSNumber alloc] init];

然后你稍后会为它分配一个不同的对象。

答案 1 :(得分:0)

我确定这是一个拼写错误,但你没有分配指针,甚至不是NSMutableArray类型,而是类型NSArray。检查行号。 2:

NSMutableArray allValuesMArray = [[NSArray alloc] init];

应该是

NSMutableArray *allValuesMArray = [[NSMutableArray alloc] init];

答案 2 :(得分:0)

您是否正在创建NSArray并将其分配给NSMutableArray?也许你的意思如下:

NSMutableArray* allValuesMArray = [[NSMutableArray alloc] init];

答案 3 :(得分:0)

以下是清理后的非泄漏形式的代码:

NSMutableArray *convertedValues = [NSMutableArray array];
// moved outside of the loop and descriptively named:
double normalizedValue = convertThis * multiply;
// make use of NSFastEnumeration -- better readability _and_ reliability
for ( NSNumber *scaleFactor in [ourDictionary objectForKey:toString] )
{
    // just in case you want to add a breakpoint to see if everything works as expected:
    double convertedValue = normalizedValue * [scaleFactor doubleValue];
    [convertedValues addObject:[NSNumber numberWithDouble:convertedValue]];
}
return convertedValues;

如果此代码出现问题,我打赌[ourDictionary objectForKey:toString]返回的数组至少包含一个不是NSNumber的实例 - NSException会在[scaleFactor doubleValue]处识别该实例。 {1}}。