在面向对象编程中,常用的就是抽象和封装,今天来完成Model,ViewModel,ViewController的编写。
日志宏定义
为了更好查看日志信息,我们封装了一些宏定义,取代了NSLog,让日志信息更方便我们调试
新建Defineds.h
#if (DEBUG || TESTCASE)
#define Log(format, ...) NSLog(format, ## __VA_ARGS__)
#else
#define Log(format, ...)
#endif
// 日志输出宏
#define BASE_LOG(cls,sel) Log(@"%@-%@",NSStringFromClass(cls), NSStringFromSelector(sel))
#define BASE_ERROR_LOG(cls,sel,error) Log(@"ERROR:%@-%@-%@",NSStringFromClass(cls), NSStringFromSelector(sel), error)
#define BASE_INFO_LOG(cls,sel,info) Log(@"INFO:%@-%@-%@",NSStringFromClass(cls), NSStringFromSelector(sel), info)
// 日志输出函数
#if (DEBUG || TESTCASE)
#define BASE_LOG_FUN() BASE_LOG([self class], _cmd)
#define BASE_ERROR_FUN(error) BASE_ERROR_LOG([self class],_cmd,error)
#define BASE_INFO_FUN(info) BASE_INFO_LOG([self class],_cmd,info)
#else
#define BASE_LOG_FUN()
#define BASE_ERROR_FUN(error)
#define BASE_INFO_FUN(info)
#endif
Model基类
在本项目中,Model命名规则都以”对象名称”+Info来命名,我们编写Model基类,新建BaseInfo类
BaseInfo.h
#import <Foundation/Foundation.h>
@interface BaseInfo : NSObject
@property(nonatomic,strong) NSString *ID;
@property(nonatomic,strong) NSString *name;
/// 初始化方法
-(instancetype) initWithDict:(NSDictionary *) dict;
/// 初始化方法
+(instancetype) infoWithDict:(NSDictionary *) dict;
/// 字典转NSArray
+(NSArray *) arrayFromDict:(NSDictionary *) dict;
/// 将数组转成对象数组
+(NSArray *) arrayFromArray:(NSArray *) array;
@end
BaseInfo.m
#import "BaseInfo.h"
@implementation BaseInfo
-(instancetype) initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
self.ID = [dict objectForKey:@"id"];
self.name = [dict objectForKey:@"name"];
//[self setValuesForKeysWithDictionary:dict];简洁写法
}
return self;
}
+(instancetype) infoWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
+(NSArray *) arrayFromDict:(NSDictionary *) dict
{
NSArray *array = [dict objectForKey:NetData];
return