我只想确保如果存在无效的 indexPath,UITableView 不会崩溃。
您可以通过检查 indexPath 的部分和行是否有效来做到这一点。
NSIndexPath* indexPath = YOUR_INDEX_PATH;
// If |isValid| is true, |indexPath| is valid, if not, |indexPath| is invalid
BOOL isValid = [TABLE_VIEW numberOfSections] > indexPath.section &&
[TABLE_VIEW numberOfRowsInSection:indexPath.section] > indexPath.row;
if (isValid) {
NSLog(@"Valid"); // Do whatever you want if |indexPath| is valid
} else {
NSLog(@"Not valid");
}
您可以向视图控制器添加测试。
- (BOOL)isValidIndexPath:(NSIndexPath *)indexPath {
return (indexPath.section < self.tableView.numberOfSections &&
indexPath.row < [self.tableView numberOfRowsInSection:indexPath.section]);
}
然后,当您需要检查索引路径时:
if ([self isValidIndexPath:indexPath]) {
...
}
作为一个类别会更好,因此所有表视图和控制器都可以使用它。
@interface UITableView (IndexPathTest)
- (BOOL)isValidIndexPath:(NSIndexPath *)indexPath;
@end
@implementation UITableView (IndexPathTest)
- (BOOL)isValidIndexPath:(NSIndexPath *)indexPath {
return (indexPath.section < self.numberOfSections &&
indexPath.row < [self numberOfRowsInSection:indexPath.section]);
}
@end
然后,对于任何表视图控制器:
if ([self.tableView isValidIndexPath:indexPath]) {
...
}