简体   繁体   中英

Data disappears after being sent with segue using Swift

I am doing something very wrong, but I don't understand what. So I sending my String like this:

var someString = "My String"
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "MyCustomIdentifier") {
        let vc = segue.destinationViewController as! MySecondViewController

        vc.someString = someString
    }
}

And MySecondViewController gets the value of someString:

var someString = String()
override func viewDidLoad() {
    super.viewDidLoad()
    print(someString) //Prints String as expected, all good
}

But then when I need it to access in imagePickerController:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    print(someString) //Nothing is printed, there is no value in someString
}

What's happening here? I need that string value in imagePickerController , because I will be sending chosen image using Alamofire and that string is my header.

EDIT: Found the problem - I was getting my someString value from server at the same time as prepareForSegue was getting called.

Strings are value types in swift, therefore the second ViewController creates a brand new instance. Need to pass a reference, so try declare it in 2nd ViewController as an optional :

var someString : String!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM