将NSString从UIViewController传递给另一个

时间:2015-08-24 22:36:29

标签: ios uiviewcontroller nsstring uistoryboardsegue swift2

我正在尝试将一个字符串值从ViewController传递给另一个:

@IBAction func unwindToMasterViewController(segue: UIStoryboardSegue) {

        let viewController:MyViewController = segue.sourceViewController as! MyViewController

        sprite = viewController.sp //sp is NSString declared in MyViewController
        print("the string is \(viewController.sp)")// nothing happens!!!


    }

在“离开”sp之前,我在日志中看到nil不是MyViewController

有更好的方法吗?

修改

我想我可能知道这个问题:

在我从@IBAction func unwindToMasterViewController(segue: UIStoryboardSegue)获取字符串值之前调用MyViewController

日志显示的顺序为:

  1. "the string is "
  2. 然后使用实际值从MyViewController打印:

    1. "sp is testString"
    2. 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我这样做了,它对我有用

 @IBAction func cancelButtonTapped(sender: UIButton) {
    self.dismissViewControllerAnimated(true, completion: nil)
    let VC = ViewController()
    let string = VC.sp
    println(string)
    delegate?.addTaskCanceled!("task canceled")

}

在主VC中我把它放在顶部:

  let sp:NSString = "Test"