很多小伙伴都会遇到这样的问题,在定义model时,要自己写很多的属性,如果碰到属性特别多的时候,只能一个一个慢慢写了,很是麻烦。下面给大家一个简单的属性生成器代码:
// 自动生成属性声明的代码
+ (void)propertyCodeWithDictionary:(NSDictionary *)dict
{
NSMutableString *strM = [NSMutableString string];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *str;
NSLog(@"%@",[obj class]);
if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")] || [obj isKindOfClass:NSClassFromString(@"NSTaggedPointerString")] || [obj isKindOfClass:NSClassFromString(@"__NSCFConstantString")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSArray *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, copy) NSDictionary *%@;",key];
}
if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
str = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
}
[strM appendFormat:@"\n%@\n",str];
}];
NSLog(@"%@",strM);
}
使用起来也很简答, 就是写一个NSObiect的Categorty, 里面写入上述方法即可!
在网络请求的返回中,直接调用该方法,实现属性列表输出,如下所示:
@property (nonatomic, assign) int instalmentPeriods;
@property (nonatomic, copy) NSString *thumbnailUrl;
@property (nonatomic, assign) int goodsStatus;
@property (nonatomic, assign) int goodId;
@property (nonatomic, copy) NSString *goodTitle;
@property (nonatomic, copy) NSString *goodsCode;
@property (nonatomic, assign) int openType;
@property (nonatomic, assign) int brandId;
@property (nonatomic, assign) int originalPrice;
@property (nonatomic, assign) int bannerId;
@property (nonatomic, assign) int directPaymentAmount;
@property (nonatomic, assign) int peroidInstalmentAmount;
@property (nonatomic, copy) NSString *goodsName;
@property (nonatomic, assign) int goodsOrder;
是不是感觉很爽,再也不用一个一个手输了,哈哈。。。