Swift协议代理始终返回nil问题求助(附相关代码)
Hey there, let's work through why your PickerDelegate is always returning nil in your GradingController—this is a super common iOS delegation pitfall, so let's break down the key checks and fixes step by step:
1. Verify Your Delegate Property Declaration
First, make sure your pickerDelegate property is declared correctly. Delegates should always be weak optional properties to avoid retain cycles, and they need to match the protocol type exactly. Your current code cuts off, but it should look like this:
weak var pickerDelegate: PickerDelegate?
weakprevents memory leaks (critical because the delegate object is likely holding a reference toGradingControlleralready)- The optional
?lets you initialize the controller without setting the delegate immediately, which is standard practice.
2. Ensure You're Assigning the Delegate Properly
A delegate will stay nil unless you explicitly set it when creating or presenting GradingController. Here's how to do it in common scenarios:
If using Storyboard Segues:
In the view controller that presents GradingController, override prepare(for:sender:):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let gradingVC = segue.destination as? GradingController else { return } // Make sure this view controller conforms to PickerDelegate! gradingVC.pickerDelegate = self }
If initializing via code:
When you create GradingController programmatically, set the delegate right after initialization:
let gradingVC = GradingController() gradingVC.pickerDelegate = self // Again, self must conform to PickerDelegate navigationController?.pushViewController(gradingVC, animated: true)
Critical Note: The object assigning the delegate (self in the examples above) must explicitly conform to PickerDelegate and implement the required updateMessage(meesage:) method.
3. Check for Typos in Protocol/Method Signatures
I noticed a small typo in your protocol method: func updateMessage(meesage: String) (extra 'e' in "meesage"). If your implementing class uses message instead of meesage, the compiler might not flag it (if the protocol is marked @objc or you're using Swift's relaxed conformance), but it's still worth fixing to avoid future issues.
4. Confirm You're Working With the Correct GradingController Instance
It's easy to accidentally create multiple instances of GradingController—for example, if you initialize one via code but present a different instance from Storyboard. Double-check that the instance you're assigning the delegate to is the exact one being displayed to the user.
5. Rule Out Retain Cycle Issues
Even if it's not the direct cause of your nil delegate, always ensure your delegate property is weak. If you omit weak, you could create a retain cycle where both GradingController and its delegate hold strong references to each other, leading to memory leaks down the line.
内容的提问来源于stack exchange,提问作者user979331

