0

There seem to be dozens of threads for this for iOS and objective C, but the only one for macOS and swift is unanswered: Access an IBOutlet from another class in Swift

In an NSTabView I have an IBOutlet for an NSPopUpButton (popup1) in another tab (Tab3) [. When I press 'Save' it collects information from all tabs, including accessing the indexOfSelectedItem property of popup1.

My approach:

  1. create an instance of Tab3, e.g. let tab = Tab3()

  2. access the outlet via tab.popup1!.indexOfSelectedItem

Error during execution: Fatal error: Unexpectedly found nil while unwrapping an Optional value And yes, Tab3's ViewController did already load at the time of execution of this command.

I believe this is because an instance of the ViewController does not have access to the IBOutlets. So, the question remains, how can I access the properties of the IBOutlet?

Cheetaiean
  • 901
  • 1
  • 12
  • 26

1 Answers1

2

How to access IBOutlets from other view controllers: Don't.

That violates the principle of encapsulation. You should treat another view controller's views as private.

I would suggest adding a function or computed property "currentlySelectedItem". From the other view controller you could query that. Note that it should return an Optional in case the outlet hasn't loaded yet or the user hasn't selected an item yet.

(your code crashes because this bit: let tab = Tab3()

Creates a new instance of your Tab3 view controller. It's views have not been loaded yet.

You will need to fix that as well. (You will need to figure out a way to get a pointer to your other view controller that's on-screen rather than creating a new instance.) How you do that depends on how you manage the view controllers in your app.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I can definitely create a function and keep the views private. However, getting a pointer to the view controller is the real problem. I created a new instance because I didn't know how to get the pointer to the on-screen Storyboard view controller, which loads from a normal segue. – Cheetaiean May 27 '21 at 21:28
  • Edit your question to show how you display the two view controllers onto the screen. Creating a new instance is NEVER the right thing to do. It's like buying a brand new car from the dealer, setting the radio to the station you want, throwing the new car away, and then wondering why the radio station on your car didn't change. – Duncan C May 28 '21 at 01:01