简体   繁体   中英

[[NSMutableArray alloc]init] causing crash

I have the following class:

#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

This class is just meant to accept data from one view, and then allow another view to fetch that data. However, whenever the insertIntoImageDataObjectsArray method is called, the line marked with asterisks causes an "EXC_BAD_ACCESS" crash. This is the call to that method:

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

Anyone have any idea why?

I expect it is this line that is crashing:

[imageDataObjectsArray insertObject:imageData atIndex:index];

And I expect it is crashing because you are attempting to insert at an index that is larger than the array.

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

[imageDataObjectsArray insertObject:@"value3" atIndex:1]; would succeed and produce

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

Subsequently calling [imageDataObjectsArray insertObject:@"value4" atIndex:5]; would fail as index 5 > max index (2)

Or as a commenter pointed out, a negative number is also invalid as an index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM