MVC架构模式
MVC架构模式
- 前言
- MVC流程
- demo
- 补充
前言
为了更好地完成天气预报的仿写,这里先学习一下MVC。
MVC 是 Model-View-Controller 的缩写,是一种经典的软件架构模式(针对系统结构和模块职责分配的一种通用解决方案)。
Model(模型):负责数据处理,包含仿写天气预报中的网络请求。
View(视图):负责UI界面,例如UIView或UITableViewCell。
Controller(控制器):View不直接修改Model,而是通过Controller连接,处理用户交互,例如UIViewController。
MVC流程
这里展示一下整个数据在MVC架构中的流动:
用户操作 → View → Controller → Model(处理数据,网络请求获取天气数据并存储)→ Controller → View(刷新UI)
demo
下面一个简单的天气预报MVC为例:
- Model:网络请求天气API数据。
#import <Foundation/Foundation.h>@interface WeatherModel : NSObject@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *temperature;- (void)fetchWeatherForCity:(NSString *)city completion:(void(^)(WeatherModel *weather, NSError *error))completion;@end#import "WeatherModel.h"@implementation WeatherModel//请求完成后回调
- (void)fetchWeatherForCity:(NSString *)city completion:(void(^)(WeatherModel *weather, NSError *error))completion {NSString *urlString = [NSString stringWithFormat:@"https://api.example.com/weather?city=%@", city];NSURL *url = [NSURL URLWithString:urlString];[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {completion(nil, error);return;}NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];WeatherModel *weather = [[WeatherModel alloc] init];weather.city = json[@"city"];weather.temperature = [NSString stringWithFormat:@"%@℃", json[@"temp"]];completion(weather, nil);}] resume];
}@end
-
View:UI界面绘制。
-
Controller:接收View的操作(点击按钮调用方法),检查输入,调用Model,发起网络请求,网络请求完成后,回调返回数据,再切回主线程更新UI。
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UITextField *cityTextField;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;- (IBAction)searchWeather:(id)sender;@end#import "ViewController.h"
#import "WeatherModel.h"@implementation ViewController//IBAction是一个和 Storyboard 上 UI 控件(比如按钮)绑定的事件方法
- (IBAction)searchWeather:(id)sender {NSString *city = self.cityTextField.text;if (city.length == 0) {self.resultLabel.text = @"请输入城市名称";return;}WeatherModel *model = [[WeatherModel alloc] init];//block回调[model fetchWeatherForCity:city completion:^(WeatherModel *weather, NSError *error) {//UI更新必须在主线程//切回主线程dispatch_async(dispatch_get_main_queue(), ^{if (!self) {return;}if (error) {self.resultLabel.text = @"获取失败";} else {self.resultLabel.text = [NSString stringWithFormat:@"%@:%@", weather.city, weather.temperature];}});}];
}
@end
这里再展示一下使用MVC架构模式完成注册登录功能的文件:
补充
这里再认识几个常见的架构模式:
- 分层模式:把系统划分成多个层次,每一层有明确的职责,只和“相邻层”通信。通常是“三层架构”:表示层、业务逻辑层、数据访问层。
- 客户端-服务器模式:是一种 分布式系统架构,将系统分为两类角色:客户端(负责与用户交互)、服务器(等待并处理来自客户端的请求)。
- 代理模式:为某个对象提供一个代理对象,由代理对象来控制对原始对象的访问。比如:通过URLSession封装远程 API 的代理类。