使用代码自动创建模型属性

每次Model中有很多的属性,写起来很费劲!这篇文章将实现一句话创建Model中的所有属性代码,输出到控制台!!!

 

NSObject+Property.h

 

#import <Foundation/Foundation.h>

@interface NSObject (Property)

+ (void)createPropertyCodeWithDictionary:(NSDictionary *)dictionary;

@end

 

NSObject+Property.m

 

复制代码
#import "NSObject+Property.h"

@implementation NSObject (Property)

+ (void)createPropertyCodeWithDictionary:(NSDictionary *)dictionary
{
    NSMutableString *strM = [NSMutableString string];

    // 遍历字典
    [dictionary enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull propertyName, id  _Nonnull value, BOOL * _Nonnull stop) {
        // NSLog(@"%@ %@",propertyName,[value class]);
        NSString *code;
        if ([value isKindOfClass:NSClassFromString(@"__NSCFString")]) {
            code = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",propertyName]
            ;
        }else 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(@"__NSCFDictionary")]){
            code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",propertyName]
            ;
        }else {
            //未完待续......
        }
        [strM appendFormat:@"\n%@\n",code];
    }];
    
     NSLog(@"%@",strM);
}

@end
复制代码

 

 

更多内容--> 博客导航 每周一篇哟!!!

 

 

有任何关于iOS开发的问题!欢迎下方留言!!!或者邮件lieryangios@126.com 虽然我不一定能够解答出来,但是我会请教iOS开发高手!!!解答您的问题!!!

posted on   人生为代码而活  阅读(386)  评论(0)    收藏  举报

编辑推荐:
· 35+程序员的转型之路:经济寒冬中的希望与策略
· JavaScript中如何遍历对象?
· 领域模型应用
· 记一次 ADL 导致的 C++ 代码编译错误
· MySQL查询执行顺序:一张图看懂SQL是如何工作的
阅读排行:
· 从被喷“假开源”到登顶 GitHub 热榜,这个开源项目上演王者归来!
· Stack Overflow,轰然倒下!
· 35+程序员的转型之路:经济寒冬中的希望与策略
· 2025年推荐6个好用的 Postman 替代工具
· 全球首位 AI 程序员 Devin 诞生了,对于程序员的影响到底多大?

导航

< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9
点击右上角即可分享
微信分享提示