Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array holds element at specific index?

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?

like image 316
iamtoc Avatar asked Sep 03 '11 06:09

iamtoc


1 Answers

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
}
like image 173
EmptyStack Avatar answered Oct 14 '22 08:10

EmptyStack