Updating UILabel from another class
-
05-07-2019 - |
Question
I'm pretty new to iPhone development and I'm still getting my head around Objective-C, so please bear with me :)
I am trying to change the text of a label from inside an object that belongs to the main view controller. Umm. I think that sounds right.
For those of you familiar with the AQRecorder
class from the SpeakHere example on the iPhone Reference Library: -
I am trying to update a label every time AQRecorder::MyInputBufferHandler
is called (i.e. when the input buffers have been filled)
My first approach was to modify the AQRecorder
class to contain a UILabel*
that I send as a parameter to the modified constructor. It worked, but it felt very wrong. And now that I want to modify a couple of different UI components I was hoping there's a better way.
I've got a feeling that I'm missing something basic. That or I'm going to require a bit of refactoring.
Solution
Look into using NSNotificationCenter
. It provides decoupled notifications, so the recorder class won't have to know anything about the UI.
OTHER TIPS
Besides notifications (as suggested by Kristopher), which are very handy if you have "global" notifications with possibly multiple observers, the classic approach that comes to mind is delegation.
In your case, the class that handles the event (AQRecorder
?) could define a delegate protocol and have a delegate property, while the class owning the UILabel
(your main view controller?) could implement this protocol and update the label in the protocol implementation (or do whatever else needs to be done).