iphone: objectAtIndex crash when tableview have no data
i have the following code
[[categories objectAtIndex:row]objectForKey:@"name"];
where categories is nsmutablearray .. it is in a tableview but if categories have 0 rows (not null) it gives exception and crash .. the exception is
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (0) beyond bounds (0开发者_JS百科)'
so how can i load the table without throw exception
An empty array will throw this exception if you try to access anything because there is never an object at any index if the array is empty. It's like me not owning a car, but you asking to borrow my car.. you cant borrow my car if I dont have one (then me throwing an exception fist at you for making me realize I'm too poor to own a car) ! =)
Do this instead:
if ([categories count]) {
[[categories objectAtIndex:row]objectForKey:@"name"];
....
}
Edit:
Actually, you would probably want to change that if
statement to make sure it has at least row + 1
number of objects.
if (([categories count] - 1) >= row) {
[[categories objectAtIndex:row]objectForKey:@"name"];
....
}
Whats wrong is that you are asking for an element of an array that doesn't exist.
精彩评论