Unwind Segue数据传递异常问题求助
Hey there, let's break down why your unwind segue's print order is flipped compared to dfri's implementation—this is a super common gotcha with how UIKit handles unwind segues under the hood!
First, let's recap the expected flow from dfri's typical setup: you'd first print the data you're about to pass from the source view controller, then print the received data in the unwind function of the target view controller. If your order is reversed, here are the most likely culprits to check:
You're triggering the segue before setting your data
This is the #1 mistake here. If you call
performSegue(or trigger the segue via storyboard action) before updating the variable you want to pass, UIKit will immediately execute the unwind function—meaning it prints the old/unset value first, then your code finally sets and prints the new variable, flipping the order.Fix this by reordering your code to assign the data first, then trigger the segue:
@IBAction func finishButtonTapped(_ sender: UIButton) { // Step 1: Set the data you want to pass self.transferData = "Updated content from source VC" print("待传递变量: \(self.transferData)") // Prints first, as expected // Step 2: Trigger the unwind segue performSegue(withIdentifier: "unwindToTargetVC", sender: self) }Your unwind function is executing unexpectedly early
Make sure your unwind action is only tied to the segue and isn't being called elsewhere (like inviewWillAppearor another lifecycle method). Also confirm the unwind function lives in your target view controller (the one you're navigating back to) and is properly linked:// Inside your target view controller @IBAction func unwindToTarget(_ segue: UIStoryboardSegue) { guard let sourceVC = segue.source as? SourceViewController else { return } let receivedData = sourceVC.transferData print("已传递变量: \(receivedData)") // Prints second, as expected }You're mixing up
prepare(for:sender:)timing
If you're usingprepare(for:sender:)to pass data, remember this method runs after you trigger the segue but before the unwind function executes. If you're printing insideprepare, make sure you're not confusing that with the unwind function's print statement—stick to printing the "to pass" value before triggering the segue, and the "received" value inside the unwind function.
The core fix here is almost always correcting the timing of data assignment vs segue execution. Double-check the order of your code in the segue-triggering action, and ensure your unwind logic only runs when the segue completes.
内容的提问来源于stack exchange,提问作者Vinny Twice

