Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Spencer Bigum
Spencer Bigum
3,250 Points

Access viewController 'view' from inside a class?

I'm wondering how do I access the view property/object that is available in a viewController from a class that I instantiate within the viewController since the class has no view object itself?

Thanks

2 Answers

Eric Haslag
Eric Haslag
9,507 Points

Hi Spencer,

There are a few ways to do this. If you're following the MVC pattern the approach to take depends on the role of the object you're instantiating in the view controller. The iOS Design Patterns course covers MVC if you're not already familiar with it. There's also a great lecture on MVC in the Developing iOS 11 Apps with Swift course (it's the second video).

If possible, it would be good if the view controller itself could update its own view to prevent coupling the view controller to the object instantiated in it.

If the object is a view, delegation is a great option. Check out the Delegation in iOS course if you're not familiar with this design pattern.

If the object is part of the model the communication channel should be even more loosely coupled because the model should never directly interface with a view. Key Value Observing (KVO) and notifications are good options for notifying the view controller that it needs to update its view. The iOS Design Patterns course covers both of these options.

Spencer Bigum
Spencer Bigum
3,250 Points

Wow Eric, Thank you so much for this in-depth answer!

Eric Haslag
Eric Haslag
9,507 Points

No problem! I hope it helps! Let me know if you have any other questions about this.