浅谈MVVM框架,以及如何去写MVVM

本文探讨了MVVM架构模式,介绍了如何在iOS应用中实现MVVM,包括M层、V层和VM层的详细代码示例。通过数据服务(DataService)对Controller进行瘦身,实现解耦。文章旨在提供一种改良版MVVM的实现思路,鼓励读者根据自身理解进行设计优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于MVVM框架,大家应该并不陌生,如果对这方面还不清楚的,可以去看一下一下三篇文章,应该会有一个比较清楚的认识。

MVVM奇葩说

iOS 架构模式--解密 MVC,MVP,MVVM以及VIPER架构

被误解的 MVC 和被神化的 MVVM

 读了这三篇文章,你应该就不会对MVVM陌生了, 我这里算是对以上几篇文章以及个人的理解,上代码展示一下自己认为的MVVM写法,当然:我这里的写法是从唐巧的猿题库里面借鉴过来的,算是对MVVM的一个变种吧。

Talk is cheap, show you the code。


用这个界面来说一下MVVM如何写~

1.M层

#import <Foundation/Foundation.h>


@interface JBSystemMessageModel : NSObject

/** 消息ID */

@property (nonatomic,assign) int messageID;

/** 作者 */

@property (nonatomic,copy) NSString *author;

/** 标题 */

@property (nonatomic,copy) NSString *title;

/** 内容 */

@property (nonatomic,copy) NSString *content;

/** 时间 */

@property (nonatomic,copy) NSString *publishedTime;

/** 是否阅读 */

@property (nonatomic,assign, readonly)BOOL isRead;


@end


2.V层(当然,严格上说Controller也是V层,但我比较喜欢把Controller看成是“502”,也就是把M、V、VM链接在一起然后展示到界面的强力胶,所以这里的V层主要展示SystemMessageCell)

#import <UIKit/UIKit.h>

#import "JBSystemMessageModel.h"


@protocol JBSystemMessageDelegate <NSObject>


@optional

- (void)moreInformation:(JBSystemMessageFrameModel *)frameModel;


@end


@interface JBSystemMessageCell : UITableViewCell


@property (nonatomic,strong) JBSystemMessageFrameModel *frameModel;


@property (nonatomic,weak) id<JBSystemMessageDelegate> delegate;


+ (instancetype)cellWithTableView:(UITableView *)tableView;


@end

SystemMessageCell.m文件,其实也就是大家常写的控件的创建(单纯的创建,不写任何业务逻辑,最后赋值还是用setFrameModel进行赋值),


@implementation JBSystemMessageCell


+ (instancetype)cellWithTableView:(UITableView *)tableView {

    

    staticNSString *reuseID =@"JBSystemMessageCell";

    

    JBSystemMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];

    

    if (!cell) {

        cell = [[JBSystemMessageCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:reuseID];

    }

    

    return cell;

}



- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

{

    if (self = [superinitWithStyle:style reuseIdentifier:reuseIdentifier]) {

        

        self.backgroundColor =BackgroundColor;

        // 点击cell的时候不要变色

        self.selectionStyle =UITableViewCellSelectionStyleNone;

        

        // 设置标题cell

        [self setUpCell];

    }

    

    return self;

}


- (void)setUpCell {

    

    // 创建控件

}


赋值:setFramModel,当然你也可以像猿题库里面那样自己写一个方法进行赋值都是可以的

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值