I am calling a method getHoleScore that populates a NSMutableArray and returns it. I’m trying to copy the array so that the calling method can access the items but I get this exception every time:
exception ‘NSRangeException’, reason: ‘* -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array’
I’ve tried multiple different ways of copying an array that I’ve found on this site but nothing seems to work. Here’s the code:
Score *theScore = self.roundScore;
NSMutableArray *scores = [[[self delegate]getHoleScore:self score:theScore] mutableCopy];
NSInteger total = 0;
if (theScore) {
self.playerName.text = theScore.name;
self.courseName.text = theScore.course;
self.hole1Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:0] integerValue]];
self.hole2Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:1] integerValue]];
self.hole3Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:2] integerValue]];
self.hole4Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:3] integerValue]];
self.hole5Field.text = [NSString stringWithFormat:@"%d", [[scores objectAtIndex:4] integerValue]];
etc.
Any idea on how to populate the scores array?
You are reaching 0 for your mutable array because it hasn’t been alloc/init yet. you either have to place this
NSMutableArray *myscores = [NSMutableArray array];above you [[self delegate] ] call.Or a better way to do this would be creating your myscores and pass the method in with a this built in nsarray super class method, which takes care of alloc/init your array.
NSMutableArray *myscores =[NSMutableArray arrayWithArray:[[self delegate] getHoleScore:self
score:theScore];
also make sure that
[[self delegate]getHoleScore:self score:theScore]is not sending you a empty array, calling a -objectAtIndex:a on a empty array will crash your code. A good way to check if your array is empty or not is calling the method -count method on your array, calling count on a array won’t crash your code, even if it’s zero.