2016-08-15 71 views
2

我实现了搜索栏。当我只搜索食物时它工作正常。但是当我尝试从搜索结果中编辑食物时,它只会改变搜索结果数组(foodSearching),但不会改变原始数组(食物)。所以当我编辑表格视图时,我需要知道原始数组(食物)的索引路径。有什么帮助吗?如何知道详细表格视图的原始细胞索引?

selectedIndexPath是“foodSearching”阵列(临时数组显示搜索结果)和“食品”阵列(原数组来保存所有的数据)

@IBAction func unwindToFoodList(sender: UIStoryboardSegue) { 
    if let sourceViewController = sender.sourceViewController as? FoodViewController, food = sourceViewController.food { 
     if let selectedIndexPath = tableView.indexPathForSelectedRow { 
      // Update an existing food. 
      if(isSearching){ 
       foodSearching[selectedIndexPath.row] = food 

       // foodSearching array is temporary.. 
       //need to find indexpath for foods array(original array)and update it as well...!! 

       tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) 

      }else{ 
       foods[selectedIndexPath.row] = food 
       tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) 
      } 

     } else { 
      // Add a new food. 
      let newIndexPath = NSIndexPath(forRow: foods.count, inSection: 0) 
      foods.append(food) 
      tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) 
     } 
     // Save the foods. 
     saveFoods() 
    } 
} 
+1

请勿编辑单​​元格。编辑你的数据模型,然后让表重新加载。除非你的模型很大,否则重新加载整个表格。 – Gargoyle

回答

1

我不会使用indexPath的建议不同参考数据,因为indexPath可以更改。如果您使用的是核心数据,我会建议objectID,但如果您不是,我会建议使用任何其他唯一可识别的信息并将其用作参考。创建下面的帮助函数可以帮助你实现:

func indexPath(forFoodWithID uniqueID: IDType) -> NSIndexPath? 
func foodID(forFoodAtIndexPath indexPath: NSIndexPath) -> IDType? 

我希望有帮助。