In my iPhone app, I need to get some values from an array like so:
string1 = [array objectAtIndex:0];
string2 = [array objectAtIndex:1];
However, sometimes, the object won’t exist in the array depending on the user data. When a line like this is called and the object doesn’t exist my app crashes naturally with an out of bounds error.
So how can I get around this? How can I detect when that object doesn’t exist and set the string accordingly?
E.g.
if object at index does exist, string = …
else if object doesn’t exist at index, string = …
NSArray has a count property you can use to determine whether an index will be valid.
If you want this to be universal functionality, you can use categories to add it as a method to NSArray: