WHAT'S THE NICEST WAY TO DO OBSERVER / OBSERVABLE IN OBJECTIVE-C (IPHONE VERSION)

Tarun Kumar

Total Post:214

Points:1642
Posted by  Tarun Kumar
 807  View(s)
Ratings:
Rate this:

I'm used to coding Java Swing UIs, and in those if you have some properties that change, and you want your UI to update, you would implement the observer/observable pattern. In Java you do this normally by having your class maintain a list of listeners that it notifies of different events.

 

I've played with Objective-C on the Mac, and that has KVC and binding which seems to work very nicely, and requires less code. The iPhone SDK doesn't seem to have this functionality though, so my question is: If I have a class that holds data that changes, what's the best way for me to register a UI component with that class so that it can be notified of changes in the data that it needs to display?

  1. Felix Pickles

    Post:24

    Points:168
    Re: What's the nicest way to do observer / observable in objective-c (iphone version)

    Every object has a reference count. When it goes to 0, the object is deallocated.

    Assuming the property was declared as @property (retain):

    Your first example, line by line:

    1.       The object is created by alloc, it has a reference count of 1.

    2.       The object is handed over to self's setAController: method, which sends it a retain message (because the method doesn't know where the object is coming from), incrementing its reference count to 2.

    3.       The calling code no longer needs the object itself, so it calls release, decrementing the reference count to 1.

    Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2.

    The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call retain if it needs that object to stick around.

    It's important to remember that self.property = foo; in Objective-C is really just shorthand for [self setProperty:foo]; and that the setProperty: method is going to be retaining or copying objects as needed.

    If the property was declared @property (copy), then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way.

    If the property was declared @property (assign), then self isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!