开发者

What's the best way for a ViewController to communicate to his model?

I'm currently relying on the fact that UIApplication is a singleton and I access the models as delegate's properties, but that开发者_高级运维 seems a long chain to me.

Controller->UIApplication->delegate->Model (->particular property to be set)


Generally speaking, the best way for a view controller to communicate with its model class is to initialize the view controller with the model class. For instance:

- (id)initWithModel:(MYModel *)aModel {
    self = [super initWithNibName:@"ModelViewController" bundle:nil];
    if (self != nil) {
        self.model = aModel;
    }
    return self;
}

There are other approaches for special cases, but this is the best default approach.


Whatever created the view controller object(s) and the needed model object can link them. For instance, a root controller can init the model, then the view controllers that needs the model, then use a property of the view controllers to provide access to the model.

Often that root level controller is the app delegate, or the view controller itself. If you just want to shorten the access chain from the app delegate as a time/space optimization, you could retain/cache the singleton model after first following the normal chain to access it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜