What is the best way to use MVC in iOS

I have been working with MVC for a long time, but I'm not sure that I use this template correctly in iOS.

This is my understanding and the source code that I use for divisions in the model view and controller.

Description:

  • Model (for example, MyModel class) Model is my data. I use the model for a specific calculation, collecting data from the Internet and then notify the dispatcher about changes in the model, for example, through NSNotificationCenter.

  • Controller (for example, the MyController class) The controller can directly contact the request for its model data and go directly to the displayed view.

  • Viewing (for example, the MyView class) Viewing - displaying and collecting events from users. The view can interact with the controller through target action and delegation.

the code:

class MyModel: NSObject

.h ... (some header code) .m Initialization method... // method for get data from internet -(NSData *)my_getDataFromInternet:(NSURL *)url{ NSData *data=[NSData dataWithContentsOfURL:url]; return data; } 

MyController class: UIVIewController

  #import "MyView.h" .h MyView * my_view; #import "MyData.h" .m Initialization method... - (void)init{ my_view = [[MyView alloc]init]; my_view.my_target = self; self.view = my_view; } -(void)mycontrolleraction{ MyData * my_data = ... [my_data my_getDataFromInternet:some_url_image]; my_view.my_image = [UIImage imageWithData:self.my_data]; } 

class MyView: UIView

  .h UIImage * my_image; property(nonatomic, assign)id my_target; .m Initialization method... - (void)initWithFrame{ UIButton * my_button = ... [button addTarget:my_target .... my_image = ... [self addSubview:my_image]; [self addSubview:my_button]; } 

I add a target to my button - my_target (my_target is my MyController). When the user clicks my button method, it is executed in MyController and requests data from my MyData class.

I would like to know where my mistake is in using this method in MVC.

+6
source share
1 answer

It sounds like you have the right idea. Usually I think of the model as storing data and also working on it, so it seems strange that the model retrieves the image and then just returns it without saving it. If the model is held onto the data, this will avoid reloading it later, but the way you have it is not, and where the data comes from, this is what should be completely up to the model.

One thing I propose that is not MVC related is this: convention for initializers . Your initialization methods should call the initializer assigned by the superclass, so your -in controller should look like this:

 -(id)init { if ((self = [super init])) { // double parens to avoid warning about = vs == my_view = [[MyView alloc] init]; // assuming my_view is an ivar my_view my_target = self; } return self; } 

The same applies to your view classes and models.

+3
source

Source: https://habr.com/ru/post/895484/


All Articles