views:

269

answers:

2

Say I have a FooController subclass of UIViewController that displays a list of Foos. What's the best practice for dealing with my foo property's lifecycle?

Do I define the @property as being read/write? It's not really -- once it's been set, changing it would potentially result in inconsistent state. Do I create the @property as readonly and write a new designated initializer, initWithFoo:(Foo *) aFoo that calls initWithNibName:bundle:? Now I have to create a new instance every time the controller is popped off the stack, and pushed on with a new foo.

The latter seems to me like the approach to take, but I've never seen anyone do this. So what's standard practice?

A: 

Objective-C is dynamic language. So don't be so strict in encapsulation. This ivar could be reached thought KVC anyways. So @property (readwrite) is OK.

Artem Tikhomirov
+3  A: 

Properties are generally the way to go. They give you power of KVC/KVO

You should set the class as an observer of the Foo property (KVO). Then everytime Foo is changed, you get a chance to deal with it. No need to worry about inconsistency.

        [self addObserver:self forKeyPath:@"foo" options:0 context:@"fooChanged"];

Then observe the change:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

     if([keyPath isEqualToString:@"foo"]){

       //do your thing


    }
}

Now it doesn't matter if foo is set in the initializer or some time later, you can deal with it. You don't want to have your code break by forcing any objects to work with you class in a predetermined order. That is very inflexible and generally bad practice. In this way you can deal with these changes gracefully.

Corey Floyd