字典轉模型簡記

1、設定一個plist字典模型
plist


2、建立模型類

  • .h方法
#import <Foundation/Foundation.h>

@interface Question : NSObject
//對應的各屬性值
@property (nonatomic,copy)NSString *answer;
@property (nonatomic,copy)NSString *icon;
@property (nonatomic,copy)NSString *title;
@property (nonatomic,strong)NSArray *options;

//設定類的實例方法和類方法,類方法用於便捷調用
-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)questionWithDict:(NSDictionary *)dict;

//關聯plist方法
+(NSArray *)questions;
@end
  • .m方法
#import "Question.h"

@implementation Question

-(instancetype)initWithDict:(NSDictionary *)dict{
    self = [super init];
    if (self) {
    //setValuesForKeysWithDictionary方法讀取字典相應數據
       [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+(instancetype)questionWithDict:(NSDictionary *)dict{
    return [[self alloc] initWithDict:dict];
}

//加載plist數組
+(NSArray *)questions{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"questions.plist" ofType:nil]];
    NSMutableArray *arrayM = [NSMutableArray array];
    for(NSDictionary *dict in array){
        [arrayM addObject:[self questionWithDict:dict]];
    }

    return arrayM;
}

//對象描述方法,顯示字典中的內容
-(NSString *)description{
    return [NSString stringWithFormat:@"<%@: %p>{answer:%@, icon:%@, title:%@, options:%@}",self.class,self,self.answer,self.icon,self.title,self.options];
}

@end

3、 控制器方法讀取

#import "ViewController.h"
#import "Question.h"

@interface ViewController ()
//設置讀取模型字典的數組屬性
@property (nonatomic,strong)NSArray *questions;
@end

@implementation ViewController
//用懶加載方式讀取模型方法
-(NSArray *)questions{
    if(_questions == nil){
        _questions = [Question questions];
    }
    return _questions;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   // 循環顯示讀取數據(該方法可實現中文轉譯)
    for(Question *obj in self.questions){
        NSLog(@"%@", obj);
    }
}
@end
發佈了22 篇原創文章 · 獲贊 0 · 訪問量 4556
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章