Search code examples
xcodeuiviewcontrolleruiapplicationdelegate

How to update a view from outside a controller in xcode


So far I have only been updated a view from within its controller. I am now in a different situation where I need to update an element in a view (a text label) based on some event occurring in another class C of my application. I realize this is basic but I am unclear what is the proper way to handle this.

  • Should I be passing my view controller in the init method of C? (Seems cumbersome to be passing in the view controller whenever I init that class C. Would require a bunch of refactoring too.)

  • Should I retrieve the app delegate from within C by calling [[UIApplication sharedApplication] delegate] and from the app delegate retrieve the view controller that I need?

Neither approaches strike me as practical or elegant.

Is there a better way?


Solution

  • The two most common methods are delegate and notification.

    In one case you give class C a delegate property and set that to be the view controller. To make it look good, you can define a delegate protocol similar to what's done for a lot of API classes. It could be passed in init but it's standard to just set the property directly.

    The other way is to have the view controller listen for a notification that class C sends when the event occurs. The view controller then makes the update when it receives notification.