iOS 字典轉模型示例

躍然發表於2015-10-13

KVC (Key - Value - Code)鍵值編碼

//  ITApp.h
#import <Foundation/Foundation.h>

@interface ITApp : NSObject

// 應用名稱
@property(nonatomic, strong) NSString *name;

// 應用圖片地址
@property(nonatomic, strong) NSString *icon;

// 應用下載量
@property(nonatomic, strong) NSString *download;

// 字典轉模型的方法
+ (instancetype)ITAppWithDictionary:(NSDictionary *)dict;

@end
//  ITApp.m
#import "ITApp.h"
#import <UIKit/UIKit.h>

@implementation ITApp

+(instancetype)ITAppWithDictionary:(NSDictionary *)dict
{
    // 建立一個 ITApp 物件
    ITApp *app = [[ITApp alloc] init];
    
    // KVC (Key - Value - Code)鍵值編碼;
    [app setValuesForKeysWithDictionary:dict];
    
    return app;
}

@end

相關文章