Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

ios - How can an outlet be nil even though it has been set

I have a viewController with two embedded viewControllers through containers. I then created outlets from the parent viewController's containers to the parent class. I want to either hide or show the containers depending on certain conditionals.

But if I simply write:

  @IBOutlet var twoArmsContainer: UIView! {
        didSet {
            print("SETTING TWO ARM")
        }
    }

 override func viewDidLoad() {
        super.viewDidLoad()
        twoArmsContainer.isHidden = true //container is nil
}

Then it crashes with twoArmsContainer being nil after the print in didSet has been triggered. How is it possible that the outlet is set, but then becomes nil? I have tried hiding it inside didSet and that works fine:

  @IBOutlet var twoArmsContainer: UIView! {
        didSet {
            print("SETTING TWO ARM")
            twoArmsContainer.isHidden = true //WORKS
        }
    }

What else can I say? The class I'm working in inherits from another class so there is a super.viewDidLoad. Not sure if that is relevant. I tried putting the outlets in the super class but with the same results. I also tried removing and readding the outlets again. Have never experienced this problem before. Let me know if I should show more code; perhaps the entire class. Not really sure what's relevant as I'm clueless of where to start.

question from:https://stackoverflow.com/questions/65898700/how-can-an-outlet-be-nil-even-though-it-has-been-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, so I found out what was wrong; an issue impossible to detect without access to the code, so in retrospect I should have posted both the parent class and container class. Sorry about that.

Anyway the issue was that the container viewController inherited from the parent viewController. This enabled me to share code in the two container viewControllers.

So the structure was basically this:

class WizardChooseArmViewController: WizardViewController {
...

This is the parent viewController which inherits from a base viewController. Then the container viewControllers looked like this:

final class WizardTwoArmsViewController: WizardChooseArmViewController {
...

Apparently it's a bad idea for containers to inherit from its parent, so I refactored and changed it to:

final class WizardTwoArmsViewController: WizardViewController {
... 

Not quite sure why its not possible for containers to inherit from its parent. Would be great if someone could brief me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...