views:

21

answers:

1

Hi!

I'd like to know if there's a way to verify if an index exists before getting it.

So it'd be way to protect my code against:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (2) beyond bounds (0)'

Like in PHP you can do: isset($object[10]); and it'll return true if it exists.

Is there such a method in Objective-C/Cocoa?

Thanks!

+1  A: 

No. But you can check if the index is above the array's count before calling -objectAtIndex:.

if (i < [array count])
   do_something_with([array objectAtIndex:i]);

Unlike PHP, Objective-C's NSArray is really an array. The indices are always numeric and consecutive. (In ObjC the associative array is called NSDictionary.)

KennyTM
Thanks, I thought there would be another way but it's working fine anyways!!!
Tom