1

Possible Duplicate:
index 0 beyond bounds for empty array error

I am a hobbyist in iOS programming. And I always have the same problem while programming. I think that I don't understand the memory management issue. This is my actual project:

h-File: a NSMutableArray containing NSStrings

NSMutableArray *pictureStrings;

@property (nonatomic,retain) NSMutableArray *pictureStrings;

in the m-File:

@synthesize pictureStrings;

and in the viewDidLoad Method

pictureStrings = [[NSMutableArray alloc] init];

in the dealloc Method

[pictureStrings release];

okay. I am working with an asynchronous URL Request which gets a number of strings and in the connectionDidFinishLoading Delegate Method the values get stored to pictureStrings

[pictureStrings addObject:aString];

BUT when I read values in the cellForRowAtIndexPath Method like

if (pictureStrings != nil) {
    cell.textLabel.text = [NSString stringWithFormat:@"%@", [pictureStrings objectAtIndex:indexPath.row]];
}

my App crashes with the message:

* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

Where is my fault? Please help me!

Yours, Raphael. Greetings from Austria

Community
  • 1
  • 1
Raphael
  • 512
  • 1
  • 6
  • 18

1 Answers1

3

Your crash is not a memory management issue. Your crash is that you're reading past the end of an array. We know that pictureStrings is non-nil at that point, because if it was nil then the objectAtIndex: method would have silently just returned nil (because messaging nil returns nil [1]). Oh and not to mention you have the if around the call to objectAtIndex: anyway - but you can safely remove that really as you shouldn't need it.

So, the only thing that can really be happening here is that your [pictureStrings addObject:aString] are not being called before the table view is reloaded. However, that would be quite odd because I assume you are doing something like return pictureStrings.count in the table view's tableView:numberOfRowsInSection: data source method. If there really were zero elements in the array then the table view wouldn't be asking for any rows and you wouldn't get this crash.

I think your problem is likely to be that you're not adding the strings to the array. You could check by breakpointing that code and seeing what is happening.

Also, consider changing your code to set the cell's text to this:

cell.textLabel.text = [pictureStrings objectAtIndex:indexPath.row];

You said they are already strings so why bother going through a stringWithFormat: call?

[1] Caveat: Doesn't always return nil - read up about it for more information.

mattjgalloway
  • 34,792
  • 12
  • 100
  • 110
  • Hi guys: It was one of my silly faults. You are right. It was no Memory-Management Issue. My idea was, to load all paths to the pictures but to show only the first 10 in the tableView. So the error was created. Thank you a lot! – Raphael Jan 10 '12 at 12:34