Model--系统原生

MVC 架构中,经常要创建各种model,而最常用的就是用系统方法setValuesForKeysWithDictionary: ,同时在model 中用setValue:forUndefinedKey:防止crash.

下面示意是一个大model的创建

ItemModel.h

#import 
#import "AtlasModel.h"
#import "CoverKeyModel.h"
#import "LabelModel.h"
#import "LikePeopleModel.h"
#import "UserModel.h"

@interface ItemModel : NSObject

//遇字典建model
@property (nonatomic,retain) AtlasModel *atlasModel;
@property (nonatomic,retain) UserModel *userModel;

//遇数组建数组
@property (nonatomic,retain) NSMutableArray *coverKeyArray;
@property (nonatomic,retain) NSMutableArray *labelsArray;
@property (nonatomic,retain) NSMutableArray *likePeopleArray;
//bool类型
@property (nonatomic,assign) BOOL isCollect;
@property (nonatomic,assign) BOOL isLike;

@end

ItemModel.M

@implementation ItemModel

//字典转model时一定要有这个方法,防止程序崩溃
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //字典中包含字典
    if ([key isEqualToString:@"atlas"]) {
        
        [self.atlasModel setValuesForKeysWithDictionary:value];
    }
    
    if ([key isEqualToString:@"user"]) {
        
        [self.userModel setValuesForKeysWithDictionary:value];
    }
    //字典中包含数组
    if ([key isEqualToString:@"labels"]) {
        
        for (NSDictionary *dic in value) {
            
            LabelModel *model = [[LabelModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.labelsArray addObject:model];
        }
    }
    
    if ([key isEqualToString:@"coverKey"]) {
        
        for (NSDictionary *dic in value) {
            
            CoverKeyModel *model = [[ CoverKeyModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.coverKeyArray addObject:model];
        }
    }
    if ([key isEqualToString:@"likePeople"]) {
        for (NSDictionary *dic  in value) {
            LikePeopleModel *model = [[LikePeopleModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.likePeopleArray addObject:model];
            
        }
    }
}

//创建子model
- (UserModel*)userModel{
    if (!_userModel) {
        _userModel = [[UserModel alloc]init];
    }
    return _userModel;
}
- (AtlasModel*)atlasModel{
    if (!_atlasModel) {
        _atlasModel = [[AtlasModel alloc]init];
    }
    return _atlasModel;
}

//数组懒加载
- (NSMutableArray*)labelsArray{
    if (!_labelsArray) {
        _labelsArray = [NSMutableArray array];
    }
    return _labelsArray;
}
- (NSMutableArray *)coverKeyArray{
    if (!_coverKeyArray) {
        _coverKeyArray = [NSMutableArray array];
    }
    return _coverKeyArray ;
}
- (NSMutableArray*)likePeopleArray{
    if (!_likePeopleArray) {
        _likePeopleArray = [NSMutableArray array];
    }
    return _likePeopleArray;
}


@end

你可能感兴趣的:(Model--系统原生)