【问题标题】:table removing index path row values from array表从数组中删除索引路径行值
【发布时间】:2012-06-21 20:58:59
【问题描述】:

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

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

    }

【问题讨论】:

    标签: objective-c arrays uitableview checkbox didselectrowatindexpath


    【解决方案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
    

    附言。您仍然需要管理单元格的检查/取消检查(就像您在上面的代码中所做的那样)。

    【讨论】:

    • 我需要数组来将值添加到 sql 语句中。
    • @Far: 好吧...在我的示例中使用names 数组似乎有什么问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    相关资源
    最近更新 更多