Я загружаю кучу стран в таблицу и позволяю пользователю удалить. Строки напрямую соответствуют массиву стран с помощью objectAtIndex: indexPath.row, и я установил для тега кнопки удаления тот же индекс.
Когда я удаляю первые пару строк, это нормально, но после этого удаляются неправильные строки и происходит сбой приложения.
Вот как я создаю строки:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
NSString *currentText;
// fill in country cell content
if ([tableView tag] == 400) {
cell = [tableView dequeueReusableCellWithIdentifier:@"SettingsCountryCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"SettingsCountryCell"];
NSLog(@"is nil");
} // it´s never nil
currentText = [arrSelectedCountries objectAtIndex:indexPath.row];
int currentRow = indexPath.row;
UILabel *countryLabel = (UILabel *)[cell viewWithTag:401];
countryLabel.text = currentText;
// create button
UIButton *countryButton = (UIButton *)[cell viewWithTag:402];
[countryButton setTag:currentRow];
[countryButton setTitle:[NSString stringWithFormat:@"row%d", currentRow]
forState:UIControlStateNormal];
NSLog(@"%@ - tag %d - title %@ - button tag %d",
currentText,
currentRow,
countryButton.titleLabel.text,
countryButton.tag);
// on load: Bulgaria - tag 2 - title row2 - button tag 2
// after one deletion (and ever after):
// Bulgaria - tag 1 - title (null) - button tag 0
[countryButton addTarget:self
action:@selector(removeCountry:)
forControlEvents:UIControlEventTouchUpInside];
}
Вот как я их удаляю (т.е. страны):
- (void)removeCountry:(UIButton *)countryButton
{
// removed country
NSString *currentText = [arrSelectedCountries objectAtIndex:countryButton.tag];
NSLog(@"removed country %@ at tag %d", currentText, countryButton.tag);
// ok: removed country All CEE Countries at tag 0
// ok: removed country Bulgaria at tag 0
// not ok: removed country Czech Republic at tag 1
// add to picker selection and remove from selected
[arrCountries addObject:currentText];
[arrSelectedCountries removeObject:currentText];
// refresh picker and country table
[countryPicker reloadAllComponents];
[countryTable reloadData];
[countryTable reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationFade];
// position table and elements below it
[self repositionForCountryChange];
}
Сначала таблица показывает: row0, row1, row2 и т. Д.
После нескольких удалений: row1, row2, row3 и т. Д.
Как только это произойдет, метка больше не будет правильно соответствовать тегу. Когда я нажимаю «Удалить» в Хорватии, кнопка «Удалить» помечена как строка 1, NSLog говорит:
removed country Czech Republic at tag 1
... и строка Хорватия не удаляется, хотя ее кнопка удаления теперь показывает row2.
А почему я получаю от NSLog:
title (null) - button tag 0
... когда я вижу в таблице, что есть заголовок, а removeCountry может получить доступ к тегу кнопки, хотя и неправильно?