美文网首页iOS
模型(Model)类创建 - iOS

模型(Model)类创建 - iOS

作者: survivorsfyh | 来源:发表于2019-11-02 14:12 被阅读0次

在日常开发中对模型 Model 的使用是必不可少的,此次以 NSObject 为例,简单举例;
首先,声明文件中声明接口中相对应需要的属性字段并实现初始化 set 方法声明,具体如下:

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface YHPersonalDataModel : NSObject

/** 头像*/
@property (nonatomic, strong) NSString *portrait;
/** 姓名*/
@property (nonatomic, strong) NSString *name;
/** 性别*/
@property (nonatomic, strong) NSString *gender;
/** 手机号*/
@property (nonatomic, strong) NSString *cellphone;
/** 证件号*/
@property (nonatomic, strong) NSString *identificationNumber;
/** 提示信息*/
@property (nonatomic, strong) NSString *hit;

+ (YHPersonalDataModel *)modelWithDic:(NSDictionary *)dic;

@end

NS_ASSUME_NONNULL_END

其次,声明好相关属性和方法后,来实现对应的方法,具体如下:

#import "YHPersonalDataModel.h"

@implementation YHPersonalDataModel

- (instancetype)initWithDic:(NSDictionary *)dic {
    if (self = [super init]) {
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

/*
 该种赋值方法也可以
 if([key isEqualToString:@"name"]) {
        self.name=value;
    }
 */
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    // 防止崩溃
#ifdef DEBUG
    NSLog(@"[YHPersonalDataModel] 相关 key 值:%@", key);
#else
#endif
}



+ (YHPersonalDataModel *)modelWithDic:(NSDictionary *)dic {
    return [[YHPersonalDataModel alloc] initWithDic:dic];
}

@end

最后,完成如上类创建后,在所需地方调用即可,一般搭配类似 TableView 这种场景居多。

YHPersonalDataModel *model = _dataPort.firstObject;
cell.model = model;

以上便是此次分享的全部内容,希望对大家有所帮助!

相关文章

网友评论

    本文标题:模型(Model)类创建 - iOS

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