views:

337

answers:

5

Hello,

if i try to access a nsmutableArray with objectAtIndex:x and if i have no object at this index, my app always crash.

So my question is: how can i check, if there is something at this index, without crashing the app?

I hope your understand my question. Thanks, Alex

+1  A: 

NSArray has a method called "count". Call count on your mutable array and it will tell you the number of elements in the array.

diciu
+3  A: 

Check if your index is in array's bounds range:

   if (index >=0 && index < [myArray count])
    ...
Vladimir
Hello, thanks for the fast reply. I know the method count, but i wanted to know if there is another solution to check if something is in an index at an array ;), Alex
Alexander
+1  A: 

If you are within the array's bounds, you will always have an object at a specific index between 0 and [array count], as the array cannot have gaps of nil values in it.

luvieere
You should never get a nil value from objectAtIndex: All elements of an NSArray are required to be non-nil.
Mark Bessey
@Mark - thanks for pointing that out.
luvieere
A: 

Try this

for(i=0; i< [myMutableArrayObject count]; i++) {
NSLog(@"%@",[[myMutableArrayObject objectAtIndex: i] myMethodDefined]);
}

Here, we are using a method predefined called count which returns the number of objects in the MutableArray Object and then another method objectAtIndex which iterates the objects at the interval from 0 to (count – 1).

Regards, Sumit

Sumit M Asok
+1  A: 

You have two options: Use the count method to ensure you're within the bounds of the array, or catch the exception when you try to use objectAtIndex: Checking the range with count will be much lower overhead than catching the exception.

In case you didn't know - there are no "holes" allowed in an NSArray - the objects from index 0 to the end of the array ([array count]-1) will all be accessible.

Mark Bessey