美文网首页iOS开发
iOS自动生成属性代码

iOS自动生成属性代码

作者: 你五哥 | 来源:发表于2018-09-26 17:34 被阅读48次
    #import <Foundation/Foundation.h>
    
    @interface NSObject (propertyCode)
    
    /**
     *  自动生成属性申明Code
     *
     *  @param dict 传入的字典
     */
    + (void)propertyCodeWithDictionary:(NSDictionary *)dict;
    
    
    
    @end
    
    
    #import "NSObject+propertyCode.h"
    #import <objc/runtime.h>
    
    @implementation NSObject (propertyCode)
    
    // 自动生成属性声明的代码
    
    + (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) NSInteger %@;",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);
    }
    
    
    • 写一个NSObject分类自动生成代码
    • 如何使用?
      在控制栏,打印
      po [NSObject propertyCodeWithDictionary:dict[@"list"][0]]
      如下图:


      image.png

    接下来只要把控制台的属性直接复制粘贴到model类里面就好了

    相关文章

      网友评论

        本文标题:iOS自动生成属性代码

        本文链接:https://www.haomeiwen.com/subject/utdjoftx.html