效果图
实现原理
- 配置Info.plist文件,加入自定义的字段:
ProjectDir : $(SRCROOT)/$(PROJECT_NAME)
- 遍历dictionary中的key和value,拼接字符串:@property(nonatomic,cop)NSString *key;
- 分类整理-纯为了简洁
- 保存到指定的.h文件中
- 用NSAssert进行了出错提示,比如没有配置ProjectDir、.h文件找不到、.h文件读取失败
配置Info.plist
实现代码-核心
PropertiesGenerator.m
// 分类
NSMutableArray *propertiesArray = [NSMutableArray array];
NSMutableArray *NSStringArray = [NSMutableArray array];
NSMutableArray *NSDictinoaryArray = [NSMutableArray array];
NSMutableArray *NSArrayArray = [NSMutableArray array];
NSMutableArray *BOOLArray = [NSMutableArray array];
NSMutableArray *floatArray = [NSMutableArray array];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *str;
if ([self class:obj isKindOfClass:@"__NSCFString"] || [self class:obj isKindOfClass:@"NSTaggedPointerString"] || [self class:obj isKindOfClass:@"__NSCFConstantString"]) {
str = [NSString stringWithFormat:@"@property(nonatomic,copy)NSString *%@;",key];
[NSStringArray addObject:str];
}
else if ([self class:obj isKindOfClass:@"__NSCFNumber"]) {
str = [NSString stringWithFormat:@"@property(nonatomic,assign)float %@;",key];
[floatArray addObject:str];
}
else if ([self class:obj isKindOfClass:@"__NSCFArray"] || [self class:obj isKindOfClass:@"__NSArrayI"]) {
str = [NSString stringWithFormat:@"@property(nonatomic,copy)NSArray *%@;",key];
[NSArrayArray addObject:str];
}
else if ([self class:obj isKindOfClass:@"__NSCFDictionary"] || [self class:obj isKindOfClass:@"__NSDictionaryI"]) {
str = [NSString stringWithFormat:@"@property(nonatomic,copy)NSDictionary *%@;",key];
[NSDictinoaryArray addObject:str];
}
else if ([self class:obj isKindOfClass:@"__NSCFBoolean"]) {
str = [NSString stringWithFormat:@"@property(nonatomic,assign)BOOL %@;",key];
[BOOLArray addObject:str];
}
}];
[propertiesArray addObjectsFromArray: NSStringArray];
[propertiesArray addObjectsFromArray: NSDictinoaryArray];
[propertiesArray addObjectsFromArray: NSArrayArray];
[propertiesArray addObjectsFromArray: BOOLArray];
[propertiesArray addObjectsFromArray: floatArray];
propertiesString = [propertiesArray componentsJoinedByString:@"\n"];
// 然后写入到.h文件中
用法
#import "PropertiesGenerator.h"
NSDictionary *dict = @{
@"name": @"zhuxuhong",
@"age": [NSNumber numberWithFloat:22],
@"nickname": @"flytoo",
@"friends": @[@"1",@"2",@"3"],
@"experience": @{@"2016": @"BISTU"},
@"password": @"1234",
@"education": @{@"2016": @"BISTU"},
@"graduated": [NSNumber numberWithBool:true]
};
[[PropertiesGenerator generator] autoGeneratePropertiesInModelClass:@"Me" Dictionary:dict]; //判断是否写入成功