偷懶啦!字典自動生成屬性列表

weixin_33912445發表於2016-09-12

在網路請求或載入plist檔案時,常會獲得一個字典。我們通常會將字典轉為模型。就避免不了在類的.h檔案宣告屬性,這是一個重複的工作,我們如何偷懶呢?

假設我們擁有一個plist檔案,我們需要對其模型化。首先我們載入這個檔案
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    // 獲取檔案全路徑
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
    
    // 檔案全路徑
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    // 設計模型,建立屬性程式碼 => dict
    [dict createPropertyCode];
}
其次我們宣告一個NSDictionary的分類,實現方法createPropertyCode

@interface NSDictionary (Property)

- (void)createPropertyCode;

@end


@implementation NSDictionary (Property)
// isKindOfClass:判斷是否是當前類或者子類
// 生成屬性程式碼 => 根據字典中所有key
- (void)createPropertyCode
{
    NSMutableString *codes = [NSMutableString string];
    // 遍歷字典
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {
        
        NSString *code;
        if ([value isKindOfClass:[NSString class]]) {
            code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];
        } else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
            code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
        } else if ([value isKindOfClass:[NSNumber class]]) {
             code = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
        } else if ([value isKindOfClass:[NSArray class]]) {
             code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
        } else if ([value isKindOfClass:[NSDictionary class]]) {
             code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
        }
        // @property (nonatomic, strong) NSString *source;
        [codes appendFormat:@"\n%@\n",code];
    }];
  
    NSLog(@"%@",codes);
}

@end
viewDidLoad執行到[dict createPropertyCode];時,就會列印出所有的屬性列表:
2016-09-12 11:23:18.646 05-Runtime(****字典轉模型****KVC****實現****)[11614:103900] **
@property (nonatomic, strong) NSString *source;

@property (nonatomic, assign) NSInteger reposts_count;

@property (nonatomic, strong) NSArray *pic_urls;

@property (nonatomic, strong) NSString *created_at;

@property (nonatomic, assign) BOOL isA;

@property (nonatomic, assign) NSInteger attitudes_count;

@property (nonatomic, strong) NSString *idstr;

@property (nonatomic, strong) NSString *text;

@property (nonatomic, assign) NSInteger comments_count;

@property (nonatomic, strong) NSDictionary *user;

這是在看小馬哥視訊時,學習到的方法,記錄下來。

相關文章