skip to Main Content

I have a separate class which when called upon updates the ToolTip (a text property) for an NSButton in a pistonViewController via its IBOutlet.
However, whenever I try to perform the action, I get the error

"Unexpectedly found nil while implicitly unwrapping an Optional value"

since pistonViewController.piston.tooltip didn’t work, I created an instance above the class:

let pistonView = pistonViewController();

and then from within the separate class called pistonView.set_piston();

func set_piston(index: Int) {
        piston1.toolTip = "yay it worked!";
    }

I get the same error: found nil.

How to get the correct instance of the pistonViewController (the one that appears on viewDidLoad) so that piston1 will not be nil?

There is this solution, but it looks needlessly complex. This one appears to only work on iOS, using a storyboard.InstantiateViewController command that does not work on MacOS. This MacOS solution is poorly explained and does not appear to work.

2

Answers


  1. Chosen as BEST ANSWER

    Ultimately I just set it up in viewDidLoad, with a timer waiting for the other program to get the variables that will then be assigned to the pistons.

    The lack of effective pointers to instances of View Controllers makes anything else not possible or perhaps just arcane and difficult.


  2. "[How do I] Modify IBOutlet property from outside of viewDidLoad"

    (But what you’re really asking is how you modify a view controller’s views from outside of the view controller.)

    The short answer is "Don’t do that." It violates the principle of encapsulation. You should treat a view controller’s view properties as private, and only modify them inside the view controller’s code.

    (To misquote Groucho Marx: "Doc, it crashes when I do this". "Then don’t do that!")

    Instead, add a public property (pistonToolTip) in your PistonViewController (Class names should begin with upper-case letters).

    class PistonViewController: UIViewController {
     
       var pistonToolTip: String {
           didSet {
               piston?.tooltip = pistonToolTip
           }
        }
    }
    

    And in case you set pistonToolTip before your PistonViewController has loaded its views, add this line to viewDidLoad:

    override func viewDidLoad() {
       super.viewDidLoad()
       piston?.tooltip = pistonToolTip
       // The rest of your viewDidLoad code
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search