这里不对各个结构的调用方式进行梳理和解释,只是针对一个应用中得代码如何区分哪部分是M,哪部分是V,哪部分是C。
个人理解如下:
MVC
M:Model
M所代表的就是针对项目中得需求对象创建的对象类型文件,比如Person,比如Car等等
V:View
V所代表的就是各种View控件,比如Label,比如Button等等
C:Controller
C所代表的就是我们IOS中得各种ViewController类,全是属于这个C。
而MVVM
M:Model
M所代表的等同于上面MVC中得M,就是数据对象类型。
V:View
V代表的就是各种界面UI空间,等同于上面的V。
VM:View-Model
VM所代表的就是一个界面数据类,在这个类中对数据进行处理,生成View所直接能够使用的对象,可能是数据,也可能是View控件,这些返回的类型能直接在Controller里进行展示。
下面粘贴从http://objccn.io/issue-13-1/粘贴过来的代码,来说明整个结构:
MVC:
@interface Person : NSObject
- (instancetype)initwithSalutation:(NSString *)salutation firstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate;
@property (nonatomic, readonly) NSString *salutation;
@property (nonatomic, readonly) NSString *firstName;
@property (nonatomic, readonly) NSString *lastName;
@property (nonatomic, readonly) NSDate *birthdate;
@end
- (void)viewDidLoad {
[super viewDidLoad];
if (self.model.salutation.length > 0) {
self.nameLabel.text = [NSString stringWithFormat:@"%@ %@ %@", self.model.salutation, self.model.firstName, self.model.lastName];
} else {
self.nameLabel.text = [NSString stringWithFormat:@"%@ %@", self.model.firstName, self.model.lastName];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
self.birthdateLabel.text = [dateFormatter stringFromDate:model.birthdate];
}
MVVM:
@interface PersonViewModel : NSObject
- (instancetype)initWithPerson:(Person *)person;
@property (nonatomic, readonly) Person *person;
@property (nonatomic, readonly) NSString *nameText;
@property (nonatomic, readonly) NSString *birthdateText;
@end
@implementation PersonViewModel
- (instancetype)initWithPerson:(Person *)person {
self = [super init];
if (!self) return nil;
_person = person;
if (person.salutation.length > 0) {
_nameText = [NSString stringWithFormat:@"%@ %@ %@", self.person.salutation, self.person.firstName, self.person.lastName];
} else {
_nameText = [NSString stringWithFormat:@"%@ %@", self.person.firstName, self.person.lastName];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE MMMM d, yyyy"];
_birthdateText = [dateFormatter stringFromDate:person.birthdate];
return self;
}
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.nameLabel.text = self.viewModel.nameText;
self.birthdateLabel.text = self.viewModel.birthdateText;
}
在这里感谢:http://objccn.io/issue-13-1/