Как я могу проверить, является ли indexPath действительным или нет в UITableView в Objective C? - PullRequest
0 голосов
/ 12 июня 2018

Я просто хочу убедиться, что UITableView не падает, если есть неверный indexPath.

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Вы можете добавить тест к вашему контроллеру представления.

- (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]) {
    ...
}
0 голосов
/ 12 июня 2018

Вы можете сделать это, проверив правильность секции и строки 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");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...