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