Design Pattern - Objective-C - MVC Model View Controller

后端 未结 2 356
Happy的楠姐
Happy的楠姐 2021-02-03 15:20

Hi I already read tutorials around the web on MVC and already read the topics on here. I think i got the concept of the MVC but i\'m not sure of its implementation.

I\'v

2条回答
  •  情话喂你
    2021-02-03 15:37

    Simply: UIViewController is not your view, it's your controller

    Think of the UIViewController as a puppeteer and the UIView as the puppet.

    • UIViewController controls WHAT is displayed on the UIView
    • UIView's main purpose is to contain subviews.
    • NSObject can be used by any class, but should be used by the UIViewController.

    Admittedly, I understood it much better after completing codeschool's tutorial http://www.codeschool.com/courses/try-ios. I highly recommend this simple hands-on approach.

    Let's break it down:

    Note: Here we utilize @property declarations instead. These will save you from writing your own setter and getter methods. (unless you need to override them for custom functionality)

    NSObject (model):

    //MyModelObject.h
    #import 
    
    @interface MyModelObject : NSObject
    
    @property (nonatomic) int count; 
    
    @end
    

    UIView (view):

    //MyView.h
    #import 
    
    @interface MyView : UIView
    
    // holds it's own subviews
    @property (strong, nonatomic) UIView *anotherView;
    @property (strong, nonatomic) UIImageView *myImageView;
    
    @end
    

    UIViewController (controller, it all comes together here!):

    //MyViewController.h
    #import 
    
    #import "MyView.h"  // your custom view
    #import "MyModel.h" // your custom model
    
    @interface MyViewController : UIViewController
    
    @property (strong, nonatomic) MyView *myView 
    // see how the view is "owned" by the view controller?
    
    @end
    
    
    
    //MyViewController.m
    
    @implementation MyViewController 
    
    @synthesize myView;
    
    
    - (void) someMethod {
    
        [myView doSomething]; 
    
    }
    
    @end
    

提交回复
热议问题