iOS MVC设计模式详解

本文介绍了MVC(Model-View-Controller)设计模式的概念及其在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 <Foundation/Foundation.h>

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

#import "User.h"

@implementation User

@end

      2.View层

#import <UIKit/UIKit.h>
#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. 执行结果截图





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风流 少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值