1

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

- (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);

    }
4

1 回答 1

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

Ps. You still have to manage checking/unchecking of cells (just as you're already doing in the code above).

于 2012-06-21T21:25:25.437 回答