[[NSMutableArray alloc] init]导致崩溃

时间:2012-10-15 16:06:52

标签: iphone objective-c

我有以下课程:

#import "SharedData.h"
static int selectedCountryIndex;
static NSMutableArray *imageDataObjectsArray;
@implementation SharedData
+(void)insertIntoImageDataObjectsArray:(ImageData *)imageData:(int)index{
    if (!imageDataObjectsArray)
        **imageDataObjectsArray = [[NSMutableArray alloc]init ];**

    [imageDataObjectsArray insertObject:imageData atIndex:index];
}
+(ImageData *)getFromImageDataObjectsArray:(int)index{
    return [imageDataObjectsArray objectAtIndex:index];
}
+(void)setSelectedCountryIndex:(int)selectedCountryIndexArg{
    selectedCountryIndex = selectedCountryIndexArg;
}
+(int)getSelectedCountryIndex{
    return selectedCountryIndex;
}
@end

此类仅用于接受来自一个视图的数据,然后允许另一个视图获取该数据。但是,每当调用insertIntoImageDataObjectsArray方法时,标有星号的行都会导致“EXC_BAD_ACCESS”崩溃。这是对该方法的调用:

[SharedData insertIntoImageDataObjectsArray:imageDataObject :[result doubleValue]-1]; 

任何人都知道为什么?

1 个答案:

答案 0 :(得分:1)

我预计这条线会崩溃:

[imageDataObjectsArray insertObject:imageData atIndex:index];

我希望它崩溃是因为你试图插入一个大于数组的索引。

0 => "value1",
1 => "value2"

[imageDataObjectsArray insertObject:@"value3" atIndex:1];会成功并产生

0 => "value1",
1 => "value3",
2 => "value2"

随后调用[imageDataObjectsArray insertObject:@"value4" atIndex:5];将失败 作为指标5>最大指数(2)

或者作为评论者指出,负数也作为索引无效