iOS-分享干货-自动生成属性的分类

  • 实际开发中,我们经常利用一些小技巧提高我们的编写代码的速度,比如给一个模型写属性,我们可以利用一个分类快速帮我们打印输出我们要写的属性;
  • 步骤
  • 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

打印示例


示例.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 1,837评论 0 9
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,242评论 6 13
  • 什么是混乱不堪,什么是废墟升烟。 究竟是什么人才能只手遮天。 问佛佛说是心里的欲念将沉与五浊世间, 愿与三恶五去结...
    々幼稚MABYE阅读 438评论 0 0
  • 身边的很多朋友经常问我,减肥期间能不能吃这个,能不能吃那个;其中问的最多的还是减肥期间能不能吃米饭的问题,下面我就...
    爱健身的小成阅读 2,160评论 5 3
  • 常常,我幻想着,未来的某一天,你右手抱着我们的孩子,左手牵着我,我牵着狗狗,夕阳往西落下,余晖洋洋洒洒地落在我们脸...
    三木木杉阅读 477评论 2 8