Reputation: 1709
if (![[array objectAtIndex:indexPath.row] isEmpty]) {
.... proceed as necessary
}
indexPath.row could hold any type of object or it could be empty. Often it is empty and thus it chokes when attempting to retrieve the object at specified location when it's null. I have tried the above approach but that doesn't work either. What is the correct way to check for this scenario?
Upvotes: 7
Views: 11041
Reputation: 51374
You should not be calling objectAtIndex:
without knowing if the array contains object at an index. Instead you should check,
if (indexPath.row < [array count])
And if you are using the array
as the data source for tableView. You should simply return [array count]
as number of rows,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [array count];
}
And, just get the object at indexPath.row without checking any conditions.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Other code
NSObject *obj = [array objectAtIndex:indexPath.row];
// Proceed with obj
}
Upvotes: 21
Reputation: 771
use the [array count]
method:
if (indexPath.row < [array count])
{
//The element Exists, you can write your code here
}
else
{
//No element exists at this index, you will receive index out of bounds exception and your application will crash if you ask for object at current indexPath.row.
}
Upvotes: 6