Check if the array saves the element at a specific index?

if (![[array objectAtIndex:indexPath.row] isEmpty]) {
   .... proceed as necessary                                 
}

indexPath.row may contain any type of object or it may be empty. Often it is empty and, thus, it is throttled when trying to get an object in the specified location, when it is zero. I tried the above approach, but this does not work either. What is the correct way to test this scenario?

+5
source share
2 answers

You should not call objectAtIndex:without knowing if the array contains an object by index. Instead, you should check

if (indexPath.row < [array count])

And if you use arrayas a data source for tableView. You should just return the [array count]number of rows,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [array count];
}

indexPath.row - .

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // Other code
    NSObject *obj = [array objectAtIndex:indexPath.row];
    // Proceed with obj
}
+14

[array count]:

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.
}
+5

All Articles