iOS MVC设计模式详解

1.概念

       M: model 模型层: 负责保存数据,继承自NSObject

       Vview视图层:负责向用户展示数据, 继承自UIVIew

       Ccontroller控制器层: 负责将model层的数据传递到view层, 继承UIViewController

2. 职责

      Model层:负责定义Model的属性

      View层:需要持有Model层的引用,在视图初始化的时候添加所有子视图,并重写model属性的setter方法来为子视图填充数据

      Controller: 需要获取Model数据,并初始化View,然后将Model赋值给View的model引用, 最后将View添加到self.view上


      MVC框架的目的是,尽可能的降低代码的耦合度(低耦合),使的每个类个职责单一化(单一职责),以便更容易的维护.


3.示例代码

        1.Model层

#import 

@interface User : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *password;
@end

#import "User.h"

@implementation User

@end

      2.View层

#import 
#import "User.h"

@interface UserView : UIView

@property (strong, nonatomic) User *user;

@end


#import "UserView.h"

@interface UserView () {
    UILabel *nameLabel;
    UILabel *passwordLabel;
}

@end


@implementation UserView
// 初始化子视图
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 50)];
        nameLabel.backgroundColor = [UIColor darkGrayColor];
        nameLabel.textColor = [UIColor whiteColor];
        [self addSubview:nameLabel];
        
        passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 300, 200, 50)];
        passwordLabel.backgroundColor = [UIColor darkGrayColor];
        passwordLabel.textColor = [UIColor whiteColor];
        [self addSubview:passwordLabel];
    }
    
    return self;
}

// 为子视图填充数据
- (void)setUser:(User *)user {
    _user = user;
    
    // 视图层展示的Label数据是从Model中获取的
    nameLabel.text = _user.name;
    passwordLabel.text = _user.password;
}

@end

       3.Controller层

#import "User.h"
#import "UserView.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1. 模拟从网络或其他位置获取数据
    User *userModel = [[User alloc] init];
    userModel.name = @"xiaohong";
    userModel.password = @"123456";
    
    // 2. 将获取的数据加载到View之上,交给View处理
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    UserView *userView = [[UserView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
    userView.user = userModel;
    [self.view addSubview:userView];
}

@end

4. 执行结果截图

iOS MVC设计模式详解_第1张图片



你可能感兴趣的:(iOS)