ios - 变量已设置但打印出 nil

标签 ios swift

我正在另一个 View Controller 中设置一个变量,它在 didSet 中工作,但在 viewdidload 中它打印出 nil

View Controller 1

    let methodView = MethodViewController()
    methodView.items = itemsSelected
    presentDetail(newVC)

View Controller 2

class MethodViewController: UIViewController {

    var items: [[String: Any]]? {
        didSet {
           print(items) // PRINTS OUT ITEMS NORMALLY
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(items) // PRINTS OUT NIL       
    }
}

最佳答案

它返回 nil,因为您正在使用一个实例设置项目,并且当您呈现屏幕并显示您的 methodViewController 时。然后你传递一个新的实例。而是使用您用来展示 Controller 的同一实例来设置项目

override func viewDidLoad() {
    super.viewDidLoad()

// Do any additional setup after loading the view.

let methodView = StackProgramViewController() //instance 1 //your case methodView
methodView.items = itemsSelected //value is set and printed


}


@IBAction func present(_ sender: Any) {

let newVc = self.storyboard?.instantiateViewController(withIdentifier: "stack") as! StackProgramViewController //instance 2 while presenting //your case newVc

newVc.items = itemsSelected //set value here with second instance nstaead of creating methodView
present(newVc, animated: true, completion: nil)

}

希望对你有帮助

关于ios - 变量已设置但打印出 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830114/

相关文章:

ios - 在 iOS xCode 项目中是否有组织文件的标准做法?

ios - iPhone 上设置的电子邮件签名在其他客户端中呈现为更大的字体大小

iphone - 有关 iPhone 中被阻止调用的信息

javascript - 获取字符串的值类型(JSContext evaluateScript)

ios - 导航 Controller 中后退按钮的放置

android - 如何使用 instagram 直接 api

ios - 如何使用 Alamofire 从 JSON 中提取数据

swift - ARKit限制节点的显示距离

ios - 表格 View 中的缓慢/断断续续的滚动

swift - 如何将手势识别器添加到 UITableViewCell 的 UIImage 和 UIButton?