gpt4 book ai didi

ios - 如何在闭包中访问类的变量?

转载 作者:行者123 更新时间:2023-11-28 10:36:50 24 4
gpt4 key购买 nike

我读了这个主题:Swift accessing class variable inside closures .但对我没有帮助。

问题

我有一个 ViewControllerData 来显示数据,还有一个 ViewControllerEdit 来编辑数据。我想将对象从 ViewControllerData 发送到 ViewControllerEdit,我使用 performSegue 来实现,但我无法从 获取编辑后的对象查看 Controller 编辑。我想在 prepare 函数中像参数一样传递闭包 (funcReturnFromEdit)。

class ViewControllerData: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableViewData: UITableView!
var saleOrder : SaleOrder? // THIS! <--------

// In this closure I want take the edited object.
let funcReturnFromEdit = { (saleEdited : SaleOrder) -> () in
self.saleOrder = saleEdited // I can't do this. Error: Value of type '(ViewControllerData) -> () -> (ViewControllerData)' has no member 'saleOrder'
}

....

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.identifier == "segueEditOrder" {
let editVc = segue.destination as! ViewControllerEdit
if saleOrder != nil {
editVc.saleOrderToEdit = saleOrder!.copy() as! SaleOrder
}
editVc.funcReturn = self.funcReturnFromEdit // <-- Not works
}
}

错误是:实例成员“saleOrder”不能用于类型“ViewControllerData”

除此之外,我不知道如何在 ViewControllerEdit 上创建此功能

class ViewControllerEdit: UIViewController, UITableViewDelegate, UITableViewDataSource {

var saleOrderToEdit : SaleOrder?

var funcReturn = { (SaleOrder) -> Void in {} } // <- This not compile. How to do this?

...
/*
Funcs to make edition...
*/

func endEditions() {
funcReturn(saleOrderToEdit) // <- Here I want send to back ViewControllerData
}
}

最佳答案

如果你需要在闭包中使用全局变量/方法,请在你的变量/方法之前放置self.

所以你可以替换这个

saleOrder = saleEdited

self.saleOrder = saleEdited

但看起来问题也在其他地方。您只需要将 saleOrder 从第一个传递到第二个 ViewController,然后在其中编辑它,然后将数据传递回第一个 View Controller

因此,首先从 ViewControllerData 中删除不必要的代码:

let funcReturnFromEdit = { (saleEdited : SaleOrder) -> () in
saleOrder = saleEdited // I can't do this.
}

并修复 ViewControllerEdit 中的完成处理程序替换

var funcReturn = { (SaleOrder) -> Void in {} }

var funcReturn : ((SaleOrder) -> ())?

还要编辑您的 endEditions 方法,因为 funcReturn 是可选的

func endEditions() {
funcReturn?(saleOrderToEdit)
}

现在只需在您的 ViewControllerData 中修复 prepare 方法来设置当用户从 ViewControllerEdit 调用 funcReturn 时应该做什么

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueEditOrder" {
let editVc = segue.destination as! ViewControllerEdit
if let saleOrderToPass = saleOrder {
editVc.saleOrderToEdit = saleOrderToPass
editVc.funcReturn = { saleEdited in
self.saleOrder = saleEdited //This code is executed when you call funcReturn?(saleOrderToEdit) from ViewControllerEdit
}
}
}
}

关于ios - 如何在闭包中访问类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53299875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com