Stephen Touset
Stephen Touset

Reputation: 2600

UIViewController subclass initialization

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?

Upvotes: 0

Views: 590

Answers (2)

Corey Floyd
Corey Floyd

Reputation: 25969

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.

Upvotes: 3

Artem Tikhomirov
Artem Tikhomirov

Reputation: 21676

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.

Upvotes: 0

Related Questions