表从数组中删除索引路径行值

时间:2012-06-21 20:58:59

标签: objective-c arrays uitableview checkbox didselectrowatindexpath

我正在尝试从选定的表行创建一个数组,以便将其推送到新视图。我的问题是从数组中删除一个未选择的行,它会抛出索引超出边界的错误,尽管我选择了其他项目。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//listOfItems is a Pre Populated Array for the table 
    NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];     
//the array i want my selected items to be added to  
     NSArray *array = names;

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];



    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

   [names addObject:cellValue];

        NSLog(@"ARRAY: %@", array);

    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;

             [names removeObjectAtIndex:indexPath.row];        

         NSLog(@"ARRAY: %@", array);  
    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];


     } 
}

如何在正在创建的数组中找到索引号,以便删除正确的值?任何帮助将不胜感激:-)谢谢!

----- -----解 这是另一种方式,以防其他人想知道。

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSString *selected = [listOfItems objectAtIndex:indexPath.row];

   if (cell.accessoryType == UITableViewCellAccessoryNone) {
      cell.accessoryType = UITableViewCellAccessoryCheckmark;

               [names addObject:selected];
             NSLog(@"ARRAY ADDED %@", names);
        }


   else {

        cell.accessoryType = UITableViewCellAccessoryNone;            

        [names removeObject:selected];   

        NSLog(@"ARRAY DELETED %@", names);

    }

1 个答案:

答案 0 :(得分:1)

如果您打算将一组已检查的单元格值传递给视图,为什么要在每个单元格选择中添加和删除对象?您可以在即将展示新视图控制器之前轻松实现此目的。像这样:

// In whatever method you have to present the new view controller
// ...
NSMutableArray *names = [[NSMutableArray alloc] initWithCapacity:0];

for (int i = 0; i < listOfItems.count; i++)
{
    if ([self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]].accessoryType == UITableViewCellAccessoryCheckmark) //Change section number if not 0
    {
        [names addObject:[listOfItems objectAtIndex:i]];
    }
}

// Pass the array now to the destination controller

聚苯乙烯。您仍然需要管理单元格的检查/取消检查(正如您在上面的代码中所做的那样)。