美文网首页
01初始MVVM

01初始MVVM

作者: myk | 来源:发表于2018-05-16 17:33 被阅读8次
    • MVVM会创建一个viewmodel层来分担ViewController的负担。
    • 创建一个Person类
    .h文件
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    - (instancetype)initWithSalutation:(NSString *)salutation firstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate;
    @property (nonatomic, copy) NSString *salutation;
    @property (nonatomic, copy) NSString *firstName;
    @property (nonatomic, copy) NSString *lastName;
    @property (nonatomic, copy) NSDate *birthdate;
    
    @end
    
    .m文件
    #import "Person.h"
    @implementation Person
    -(instancetype)initWithSalutation:(NSString *)salutation firstName:(NSString *)firstName lastName:(NSString *)lastName birthdate:(NSDate *)birthdate{
        if (self = [super init]) {
            self.salutation = salutation;
            self.firstName = firstName;
            self.lastName = lastName;
            self.birthdate = birthdate;
        }
        return self;
    }
    @end
    
    • 创建一个ViewModel层,来写逻辑
    .h文件
    #import <Foundation/Foundation.h>
    #import "Person.h"
    @interface ViewModel : NSObject
    @property (nonatomic) Person *person;
    @property (nonatomic, copy, readonly) NSString *nameText;
    @property (nonatomic, copy, readonly) NSString *birthdateText;
    -(instancetype)initWithPerson:(Person *)person;
    @end
    
    .m文件
    #import "ViewModel.h"
    @implementation ViewModel
    -(instancetype)initWithPerson:(Person *)person{
        if (self = [super init]) {
            _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
    
    • 现在我们已经把逻辑给写完了,我们只需要在VC里面获取到VM接口文件里面的属性就可以了
    .m文件
    //<通过VC里面的VM属性,获取到VM的属性值>
    #import "ViewController.h"
    #import "ViewModel.h"
    @interface ViewController ()
    @property (nonatomic) ViewModel *vm;
    @end
    @implementation ViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        Person *p = [[Person alloc] initWithSalutation:@"Hello" firstName:@"MYK" lastName:@"KE" birthdate:[NSDate dateWithTimeIntervalSince1970:0]];
        self.vm = [[ViewModel alloc] initWithPerson:p];
        NSLog(@"name === %@, birthday === %@",self.vm.nameText, self.vm.birthdateText);
    }
    @end
    

    相关文章

      网友评论

          本文标题:01初始MVVM

          本文链接:https://www.haomeiwen.com/subject/cixmdftx.html