- 实际开发中,我们经常利用一些小技巧提高我们的编写代码的速度,比如给一个模型写属性,我们可以利用一个分类快速帮我们打印输出我们要写的属性;
- 步骤
- 1.给NSObject写分类
- 2.提供一个类方法,方便调用(如果写成对象方法,还必须先创建一个对象才能调用,所以优先类方法)
- 3.调用分类的方法,传入字典;
- 代码:
#import <Foundation/Foundation.h>
@interface NSObject (Property)
+ (void)creatPropertyCodeWithDictionary:(NSDictionary *)dict;
@end
#import "NSObject+Property.h"
@implementation NSObject (Property)
+ (void)creatPropertyCodeWithDictionary:(NSDictionary *)dict
{
NSMutableString *strM = [NSMutableString string];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull propertyName, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *code;
if ([value isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,assign) int %@;",propertyName];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFArray")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSArray *%@;",propertyName];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFString")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSString *%@;",propertyName];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSDictionary *%@;",propertyName];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,assign) BOOL %@;",propertyName];
};
[strM appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",strM);
}
@end
打印示例