Swift 中 VC 之间的短期记忆

Short Term Memory Between VCs in Swift

简写为:

VC 的变量的值在另一个 VC 的模态呈现和解雇期间是否保持不变?当第二个 VC 被关闭时,原始 VC 的变量是否仍然等于它们最后的值?

详细信息,如果需要

我有一个 viewController,其中选择了一个 table 单元格。然后将该单元格的内容拉出并传递给编辑器 viewController,如下所示:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    //Segue to mainVC editor, for editing action
    if (segue.identifier == "modalToEditor") && passingEdit == true {
        //Assign selection to a variable 'currentCell'
        let indexPath = tableView.indexPathForSelectedRow;
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! CustomTableViewCell;

        //Set cell text into variables to pass to editor
        let cellNameForEdit = currentCell.nameLabel!.text
        let cellDescForEdit = currentCell.descLabel.text

        //Pass values to EditorView
        let editorVC = segue.destinationViewController as! EditorView;
        editorVC.namePassed = cellNameForEdit
        editorVC.descPassed = cellDescForEdit
        editorVC.indexOfTap = indexPath
        editorVC.currentListEntity = currentListEntity

现在,在 second/editor viewController 中,用户可以点击一个要求移动单元格的按钮。 "move screen" 是 different/third VC。我想知道的是,我可以关闭编辑器并期望原始 VC 记住最后选择的单元格吗?

附加编辑以显示 cellForRowAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    //Setup variables
    let cellIdentifier = "BasicCell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell

    //Make sure the row heights adjust properly
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 80.0


    //Create normal cells except when last cell
    if indexPath.row < taskList_Cntxt.count {
        let task =  taskList_Cntxt[indexPath.row]
        //Create table cell with values from Core Data attribute lists
        cell.nameLabel!.text = task.valueForKey("name") as? String
        cell.descLabel!.text = task.valueForKey("desc") as? String

        //Related to running TaskActions: Empty block function passed from custom cell VC
        cell.doWork = {
            () -> Void in
            self.doStuff(cell)
        }
    }

是的。视图控制器只是对象,因为它们的属性只有在执行更改它们的代码时才会更改。在您的特定情况下, VC 将其 table 视图保留为 属性 (并且强烈地作为其视图的子视图),并且 table 视图保留了一个选定的数组索引路径。不过要小心,UITableViewController 的子类可以默认清除 viewWillAppear (see here) 上的选择。

另请注意,您选择了大多数人认为在 prepareForSegue 中初始化 editorVC 的奇怪方法。获取选定的索引路径很好,但是获取单元格(视图),然后配置该单元格,然后从单元格的子视图中获取数据源值是非常迂回的。

看到 cellForRowAtIndexPath 方法中的 let task = taskList_Cntxt[indexPath.row] 行了吗?这就是您在给定 indexPath 处访问数据源数组中的对象的方式。该对象(您所谓的 task)应该传递给下游视图控制器。