iOS------MVC模式

什么是MVC

MVC(Model—View—Controller,模型—视图—控制器)是软件工程中的一种软件架构模式,它把软件系统分为三个基本模式:模型(model),视图(view),控制器(Controller)。MVC不是一种设计方式(design Pattern), 而是一种架构模式(Architectural Pattern),用于描述应用程序的结构以及结构各个部分的职责和交互方式

MVO的三层架构

模型(Model):数据模型用于封装与应用程序的业务逻辑相关的数据以及对数据的处理方法。模型又对数据直接访问的权利,例如对数据库的访问。“模型”不依赖“视图”和“控制器”,也就是说,模型不关心他是如何显示和如何备操作。但是模型中数据的变化一般回通过一种刷新机制被公布。为了实现这种机制,那些用于监视次模型的视图必须事先在此模型上注册,从而,视图可以了解在数据模型上发生的变化。

视图(View):视图层能够实现数据有目的的显示。在视图中一般没有程序上的逻辑。为了实现视图上的刷新功能,视图需要访问它监视的数据模型,因此应该实现在被它监视的数据那里注册。

控制器(Controller):控制器起到不同层面的组织关系,用于控制应用程序的流程。它处理事件并做出相应。“事件”包括用户的行为和数据模型上的变化。

MVC的原理

在这里插入图片描述
1, Controller和View之间可以通信,Controller通过outlet(输出口)控制View可以通过target-action,delegate或者data source(想想UItableViewDataSourse)来和Controller通信。

2,Controller接受到View传过来的交互事件(view就是完成让人和程序的交互的,比如按钮)之后,经过一些判断和处理,把需要Modal处理的事件递交给Model处理(比如保存到数据库),Controller对Model使用的是API。

3,Model在处理完数据之后,如果有需要,回通过Notification或者KVO的方式告知Controller,事件处理完成,controller再经过判断和处理之后,考虑下一步怎么办(是在后台默默无闻操作,还是需要更新View)。这里的无线天线很有意思,Model只负责发送通知,具体谁接受这个通知并处理它,Model并不关心,这一点是理解NOtification模式的关键。

4,Model和View之间不直接通信;

MVC的优点和缺点

MVC的一个最明显好处就是它将视图展示和应用逻辑清晰的分离开来。对不同用户以及不同设备类型的支持一直是当下的一个常见问题,例如:来自台式电脑和手机的请求所得到的视图应该是不相同的,模型会返回完全相同的数据,但是不同的地方是控制器会选择使用的视图文件来展示数据(我们可以把它看作是不同的模板)。除了将视图从业务逻辑中分离开外,MVC的分离也降低了大型应用设计的难度,代码也更具结构性,因此也更容易维护,测试和重用。

MVC模式的缺点是由于它没有明确的定义,所以完全理解MVC模式并不是很容易。使用MVC模式需要精心的计划,由于它的内部原理比较复杂,所以需要花费一些时间去思考。开发一个MVC模式架构的工程,将不得不花费相当可观的时间去考虑如何将MVC模式运用到应用程序中,同时由于模型和视图要严格的分离,这样也给调试应用程序带来了一定的困难。每个构件在使用之前都需要经过彻底的测试。另外由于MVC模式将一个应用程序分成了三个部件,所以这意味着同一个工程将包含比以前更多的文件。

具体代码
以登录注册页面为例
登录界面
Model

//landingModel.h
@interface LandingModel : NSObject
@property (nonatomic, strong) NSMutableArray* userArray;
@property (nonatomic, strong) NSMutableArray* passwordArray;
- (void)landingMassageInit;
@end
//landingNodel.m
#import "LandingModel.h"

@implementation LandingModel
- (void)landingMassageInit {
    self.userArray = [[NSMutableArray alloc] init];
    self.passwordArray = [[NSMutableArray alloc] init];
    [self.userArray addObject:@"fuchuang"];
    [self.passwordArray addObject:@"fu135453"];
}
@end

View

//landingView.h
@interface LandingView : UIView
@property (nonatomic, strong) UITextField* userTextField;
@property (nonatomic, strong) UITextField* passwordTextfield;
@property (nonatomic, strong) UIButton* landingButton;
@property (nonatomic, strong) UIButton* registerButton;
@end
landingView.m
#import "LandingView.h"

@implementation LandingView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor whiteColor];
    self.userTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 200, 175, 60)];
    self.userTextField.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
    self.userTextField.placeholder = @"输入用户名";
    [self addSubview:self.userTextField];
    
    self.passwordTextfield = [[UITextField alloc] initWithFrame:CGRectMake(100, 300, 175, 60)];
    self.passwordTextfield.placeholder = @"输入密码";
    self.passwordTextfield.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
    [self addSubview:self.passwordTextfield];
    
    self.landingButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.landingButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.landingButton setFrame:CGRectMake(100, 400, 75, 30)];
    [self addSubview:self.landingButton];
    
    self.registerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.registerButton setFrame:CGRectMake(200, 400, 75, 30)];
    [self addSubview:self.registerButton];
    
    return self;
}

@end

Controller

//LandingController.h
#import <UIKit/UIKit.h>
#import "LandingView.h"
#import "LandingModel.h"
#import "RegisterController.h"
NS_ASSUME_NONNULL_BEGIN

@interface LandingController : UIViewController<RegisterControllerDelegate>
@property (nonatomic, strong) LandingView* landingView;
@property (nonatomic, strong) LandingModel* landingModel;

//- (void)passName:(NSString*) name andPassPassword:(NSString*) password;

@end

NS_ASSUME_NONNULL_END

//landingController.m
#import "LandingController.h"

@interface LandingController ()

@end

@implementation LandingController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.landingView = [[LandingView alloc] init];
    self.landingView.frame =
    CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    [self.landingView.registerButton addTarget:self action:@selector(pressRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.landingView.landingButton addTarget:self action:@selector(pressLanding) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.landingView];
    
    self.landingModel = [[LandingModel alloc] init];
    [self.landingModel landingMassageInit];
    
}
- (void)pressRegister {
    RegisterController* registerViewController = [[RegisterController alloc] init];
    registerViewController.modalPresentationStyle  = UIModalPresentationOverFullScreen;
    registerViewController.existUserArray = self.landingModel.userArray;
    registerViewController.delegate = self;
    [self presentViewController:registerViewController animated:YES completion:nil];
}
- (void)pressLanding {
    BOOL flag = NO;
    for (int i = 0; i < self.landingModel.userArray.count; i++) {
        if ([self.landingView.userTextField.text isEqualToString:self.landingModel.userArray[i]] && [self.landingView.passwordTextfield.text isEqualToString:self.landingModel.passwordArray[i]]) {
            flag = YES;
            break;
        }
    }
    if (flag == YES) {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"登录成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"帐号或密码错误!" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
                [alert addAction:sure];
                [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)registerReturn:(NSString *)namestr andPass:(NSString *)passStr {
    [self.landingModel.userArray addObject:namestr];
    [self.landingModel.passwordArray addObject:passStr];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

注册页面
Model

//RegisterModel.h
#import <Foundation/Foundation.h>


NS_ASSUME_NONNULL_BEGIN

@interface RegisterModel : NSObject
@property (nonatomic, strong) NSMutableArray* userArray;
- (void)registerMassageInit;
- (void)registerNassageAdd:(NSMutableArray *)arrayAdd;
@end

NS_ASSUME_NONNULL_END

//registerModel.m
#import "RegisterModel.h"
@implementation RegisterModel
- (void)registerMassageInit {
    self.userArray = [[NSMutableArray alloc] init];
}
- (void)registerNassageAdd:(NSMutableArray *)arrayAdd {
    [self.userArray addObjectsFromArray:arrayAdd];
}
@end

View

//registerView.m
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface RegisterView : UIView
@property (nonatomic, strong) UITextField* userTextField;
@property (nonatomic, strong) UITextField* password01Textfield;
@property (nonatomic, strong) UITextField* password02Textfield;
@property (nonatomic, strong) UIButton* registerButton;
@end

NS_ASSUME_NONNULL_END
//RegisterView.h
#import "RegisterView.h"

@implementation RegisterView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor whiteColor];
    self.userTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 200, 175, 60)];
    self.userTextField.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
    self.userTextField.placeholder = @"输入用户名";
    [self addSubview:self.userTextField];
    
    self.password01Textfield = [[UITextField alloc] initWithFrame:CGRectMake(100, 300, 175, 60)];
    self.password01Textfield.placeholder = @"输入密码";
    self.password01Textfield.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
    [self addSubview:self.password01Textfield];
    
    self.password02Textfield = [[UITextField alloc] initWithFrame:CGRectMake(100, 400, 175, 60)];
    self.password02Textfield.placeholder = @"请确认密码";
    self.password02Textfield.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
    [self addSubview:self.password02Textfield];
    
    self.registerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.registerButton setFrame:CGRectMake(200, 500, 75, 30)];
    [self addSubview:self.registerButton];
    return self;
}
@end

Controller

//RegisterController.h
#import <UIKit/UIKit.h>
#import "RegisterView.h"
#import "RegisterModel.h"

NS_ASSUME_NONNULL_BEGIN
@protocol RegisterControllerDelegate <NSObject>

- (void) registerReturn:(NSString*) namestr andPass: (NSString*) passStr;

@end

@interface RegisterController : UIViewController
@property (nonatomic, assign) id<RegisterControllerDelegate> delegate;
@property (nonatomic, strong) NSMutableArray* existUserArray;
@property (nonatomic, strong) RegisterModel* registermodel;
@property (nonatomic, strong) RegisterView* registerView;
@property (nonatomic, strong) UIAlertController* alert;
@end

NS_ASSUME_NONNULL_END
//registerController.m
#import "RegisterController.h"

@interface RegisterController ()

@end

@implementation RegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.registerView = [[RegisterView alloc] init];
    self.registerView.frame =
    CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    [self.registerView.registerButton addTarget:self action:@selector(pressRegister) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.registerView];
    
    self.registermodel = [[RegisterModel alloc] init];
    //[self.registermodel.userArray addObjectsFromArray:self.existUserArray];]
    [self.registermodel registerNassageAdd:self.existUserArray];
    [self.registermodel registerMassageInit];
}
- (void)pressRegister {
    if ([self.registerView.userTextField.text isEqualToString:@""] == YES || [self.registerView.password01Textfield.text isEqualToString:@""] == YES || [self.registerView.password02Textfield.text isEqualToString:@""] == YES)
    {
        
        self.alert = [UIAlertController alertControllerWithTitle:@"警告⚠️" message:@"输入项不能为空" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) {}];
        [self.alert addAction:action];
        [self presentViewController:self.alert animated:YES completion:nil];
        
        //[self.delegate registerReturn:self.textFiled1.text andPass:self.textFiled2.text];
    } else {
        for (int i = 0; i < self.registermodel.userArray.count; i++) {
            //NSLog(@"----");
            //NSLog(@"%@", self.array1[i]);
            if ([self.registerView.userTextField.text isEqualToString:self.registermodel.userArray[i]]) {
                self.alert = [UIAlertController alertControllerWithTitle:@"" message:@"账号已注册" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) {}];
                [self.alert addAction:action];
                [self presentViewController:self.alert animated:YES completion:nil];
                return;
            }
        }
        [self.delegate registerReturn:self.registerView.userTextField.text andPass:self.registerView.password01Textfield.text];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    }
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值