commitEditingStyle с проблемами сгруппированных таблиц - PullRequest
1 голос
/ 10 мая 2011

Мне тяжело оборачиваться вокруг этого.Я загружаю массив NSMutable из файла plist и заполняю сгруппированную таблицу данными.Таблица состоит из 3 разделов, раздел 0 не редактируется, но два других - у меня работает это ограничение.Моя проблема, когда пользователь выбирает удалить строку в двух редактируемых разделах.Я считаю, что это потому, что у меня есть два ключа для каждой записи - один для его имени, а другой для его URL.

Вот образец моего списка.Ключ заголовка используется для названий разделов.Затем есть ключ для «Rows» - текст, который отображается в каждой ячейке, а затем «url», который при выборе строки загружает URL в веб-просмотре.Я знаю, что хочу захватить раздел и строку, которые выбрал пользователь, а затем удалить «Строка» и «URL» для этого индекса.Любая помощь будет принята с благодарностью.

Вот мой список:

<array>
<dict>
<key>Title</key>
<string>Query</string>
    <key>Rows</key>
    <array>
        <string>Non-editable String 1</string>
        <string>Non-editable String 2</string>
        <string>Non-editable String 3</string>
        <string>Non-editable String 4</string>
    </array>
</dict>
<dict>
    <key>Title</key>
    <string>Resources</string>
    <key>Rows</key>
    <array>
        <string>Website Name 1</string>
        <string>Website Name 2</string>
        <string>Website Name 3</string>
        <string>Website Name 4</string>
        <string>Website Name 5</string>
    </array>
    <key>url</key>
    <array>
        <string>http://website1.com</string>
        <string>http://website2.com</string>
        <string>http://website3.com</string>
        <string>http://website4.com</string>
        <string>http://website5.com</string>
    </array>
</dict>
<dict>
    <key>Title</key>
    <string>Monitoring</string>
    <key>Rows</key>
    <array>
        <string>Website Name 6</string>
        <string>Website Name 7</string>
        <string>Website Name 8</string>
    </array>
    <key>url</key>
    <array>
        <string>http://website6.com</string>
        <string>http://website7.com</string>
        <string>http://website8.com</string>
    </array>
</dict>

Это ограничивает редактирование двумя последними разделами

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView     editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0)
    return UITableViewCellEditingStyleNone;
else
    return UITableViewCellEditingStyleDelete;
}

Этоis (нерабочий код) для фиксации удаления (tableData - это имя моего изменяемого массива).Мое приложение бомбит по адресу:

        [[self.tableData objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row];

Но угадывать deleteRowsAtIndexPaths тоже неправильно.Код:

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {

    [self.tableView beginUpdates];
    [[self.tableData objectAtIndex:indexPath.section] removeObjectAtIndex:indexPath.row];

    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath.row] withRowAnimation:UITableViewRowAnimationFade];

    [self.tableView endUpdates];
    [self.tableView reloadData];
}



--- ОБНОВЛЕНИЕ --- Если я делаю это таким образом и устанавливаю раздел и строку в NSUInteger, когда я регистрирую это,правильный раздел и строка записываются в журнал.Тем не менее, у меня сбой на

[[self.tableData objectAtIndex:section] removeObjectAtIndex:row];

В моей консоли я получаю эту ошибку: Завершение приложения из-за необработанного исключения «NSInvalidArgumentException», причина: '- [__ NSCFDictionary removeObjectAtIndex:]:нераспознанный селектор отправлен на экземпляр 0x4b43b20 '

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {

    NSUInteger row = [indexPath row];
    NSLog(@"NSUInteger Row: %d", row);

    NSUInteger section = [indexPath section];
    NSLog(@"NSUInteger Section: %d", section);

    [self.tableView beginUpdates];

    [[self.tableData objectAtIndex:section] removeObjectAtIndex:row];

    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:section]] withRowAnimation:UITableViewRowAnimationFade];

1 Ответ

1 голос
/ 13 мая 2011

Для вашего plist переменная tableData - это NSMutableArray, которая содержит 3 объекта, каждый из которых является NSMutableDictionary (несмотря на то, что в документах говорится, что это должен быть NSDictionary - immutable .быть NSArrays - неизменяемым).

Независимо от того, после прочтения plist объекты, которые вы хотите изменить, должны так или иначе быть изменяемыми по умолчанию или при явном вызове mutableCopy.

В методе commitEditingStyle вам нужно вызывать removeObjectAtIndex для массивов, а не для словаря разделов.Поэтому сначала получите ссылку на массивы Rows и url (вы должны сделать что-то подобное в cellForRowAtIndexPath для отображения значений).

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        NSMutableDictionary *sectionDict = [tableData objectAtIndex:indexPath.section];
        NSMutableArray *sectionRows = [sectionDict objectForKey:@"Rows"];
        NSMutableArray *sectionUrls = [sectionDict objectForKey:@"url"];

        [sectionRows removeObjectAtIndex:indexPath.row];
        [sectionUrls removeObjectAtIndex:indexPath.row];

        //don't need beginUpdates (we're making only one delete call)           
        //tableView beginUpdates];

        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
                withRowAnimation:UITableViewRowAnimationFade];

        //don't need endUpdates (since we're not doing beginUpdates)
        //[tableView endUpdates];

        //don't need reloadData since we're calling deleteRowsAtIndexPaths
        //(or call reloadData instead of deleteRowsAtIndexPaths)
        //[tableView reloadData];
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...