iOS MVC设计模式详解
来源:互联网 发布:航天信息软件下载 编辑:程序博客网 时间:2024/05/16 13:50
1.概念
M: model 模型层: 负责保存数据,继承自NSObject
V: view视图层:负责向用户展示数据, 继承自UIVIew
C: controller控制器层: 负责将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. 执行结果截图
0 0
- iOS MVC设计模式详解
- iOS中MVC等设计模式详解
- iOS巅峰之MVC(设计模式)详解
- iOS巅峰之MVC(设计模式)详解
- iOS 设计模式MVC
- iOS设计模式---MVC
- ios mvc设计模式
- iOS MVC设计模式
- iOS MVC设计模式
- iOS MVC设计模式
- MVC设计模式详解
- MVC设计模式详解
- MVC设计模式详解
- MVC设计模式详解
- 详解MVC设计模式
- MVC设计模式详解
- IOS设计模式:MVC模式
- iOS开发设计模式-MVC
- Linux 进程栈和线程栈的区别
- zabbix二次开发集成运维平台展现监控图表
- 树的判定
- 在.net中调用别人写的接口获得数据
- ARP spoofing 实验与分析
- iOS MVC设计模式详解
- 常用SQL语句
- Linux 下的 Redis 安装 && 启动 && 关闭 && 卸载
- python3中安装easygui的问题解决
- SRVCTL 中failover_method 解释
- 处理js跨域问题方法汇总
- 数据库操作
- 在linux下如何判断是否已经安装某个软
- Java设计模式之观察者模式