0

我不确定这个循环到底有什么问题,但是每当我运行它时,我都会不断收到 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

4 回答 4

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

于 2011-01-24T12:35:17.767 回答
0

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

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

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

您也可以在将产品添加到数组之前检查它是否不为零。

而且你有内存泄漏。

product = [[NSNumber alloc] init];

然后您稍后为其分配一个不同的对象。

于 2011-01-21T08:49:34.627 回答
0

我确定这是一个错字,但是您没有分配指针,甚至没有分配 type of NSMutableArray,而是 type NSArray。检查行号 2:

NSMutableArray allValuesMArray = [[NSArray alloc] init];

它应该是

NSMutableArray *allValuesMArray = [[NSMutableArray alloc] init];
于 2011-01-21T08:50:10.787 回答
0

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

NSMutableArray* allValuesMArray = [[NSMutableArray alloc] init];
于 2011-01-21T08:50:26.950 回答