I am trying to hide the last row, if some conditions in my app is met, but if I select the last row in my UITableView my app crashes with.
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 11 beyond bounds [0 .. 10]'
This error makes sense, but I don't know how I can fix it.
In my cellForRowAtIndexPath method:
NSInteger rowsToDisplay = 0;
if (self.restaurants.count > 0) {
if(indexPath.section == 0)
{
rowsToDisplay = indexPath.row;
if([Restaurant getRestaurantFromRemoteID:[[NSUserDefaults standardUserDefaults] objectForKey:kRestaurantId]].orderSessionActive.boolValue && indexPath.row >= [Restaurant indexPathForRestaurant:[Restaurant getRestaurantFromRemoteID:[[NSUserDefaults standardUserDefaults] objectForKey:kRestaurantId]] inArray:self.restaurants].row)
{
rowsToDisplay = indexPath.row + 1;
}
}
restaurant = self.restaurants[rowsToDisplay];
}
and the numberOfRowsInSection: method.
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchBarDisplayContr.searchResultsTableView) {
return [self.searchResults count];
} else {
if ([Restaurant getRestaurantFromRemoteID:[[NSUserDefaults standardUserDefaults] objectForKey:kRestaurantId]].orderSessionActive.boolValue) {
if (section == 0) {
return [self.restaurants count] - 1;
}
}else {
return [self.restaurants count];
}
}
return 0;
}
The above code works and hides the selected cell if the cell is not the last cell in the tableView. How can I get this also to work when the last cell is selected?
rowsToDisplay = indexPath.row + 1;
I think this line causes out of bounds error. I don't know why you're increasing the index by one, but :
if([Restaurant getRestaurantFromRemoteID:[[NSUserDefaults standardUserDefaults] objectForKey:kRestaurantId]].orderSessionActive.boolValue && indexPath.row >= [Restaurant indexPathForRestaurant:[Restaurant getRestaurantFromRemoteID:[[NSUserDefaults standardUserDefaults] objectForKey:kRestaurantId]] inArray:self.restaurants].row)
{
if(indexPath.row + 1 < [self.restaurants count])
rowsToDisplay = indexPath.row + 1;
}
Will fix the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.