设置变量但打印出零

时间:2017-08-23 03:21:41

标签: ios swift

我在另一个viewcontroller中设置一个变量,它在didSet内部工作,但在viewdidload中打印出nil

ViewController 1

<div ng-controller="AppCtrl">
    Hello {{name}}
</div>
var app = angular.module('app',[]);
function AppCtrl($scope) {
    $scope.name = 'Sally';
}

ViewController 2

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

2 个答案:

答案 0 :(得分:1)

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

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)

}

希望有所帮助

答案 1 :(得分:1)

为什么不在类上使用初始化方法,然后将其显式传递给当前方法,如下所示:

MethodViewController

class MethodViewController: UIViewController {

    var items: [[String: Any]]?

    init(withItems items:[[String: Any]]?) {
        self.items = items
        super.init(nibName: "MethodViewController", bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        print(items);
    }
}

上一个视图控制器

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let items = [["Stack":"Overflow"]]
        let methodView = MethodViewController(withItems: items)
        self.present(methodView, animated: true, completion: nil)
    }
}

我已经测试了它,它将打印出传递的项目,还要注意编译器强制你拥有的require init()方法。您还需要根据设置视图的方式指定bundle和nibName。

我应该注意这种方法是,如果您不是从故事板加载,而是从具有相同名称的单独.xib文件加载。