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

    } 

回答

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。你仍然必须管理单元格的检查/取消选择(就像你已经在上面的代码中做的那样)。

+0

我需要数组将值添加到sql语句中。 – Far

+0

@Far:好的...以及我的例子中使用'names'数组似乎是什么问题? – Alladinian

+0

修复了我的问题,谢谢。 – Far