John Roberts
John Roberts

Reputation: 5976

[[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?

Upvotes: 0

Views: 363

Answers (1)

James Webster
James Webster

Reputation: 32066

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

Upvotes: 1

Related Questions