天天看點

iOS資料處理之字典轉模型

當程式中有需要用到plist檔案去存儲一些東西的時候,我們在程式中也需要動态地去擷取到plist檔案中的内容并且使用它們。在MVC設計模式中,M指的是modal,代表着程式需要的資料,是以我們需要建立一個modal類然後處理plist檔案中的資料或者是其他的來源,本文主要講處理plist檔案,而這個過程也就是本文要讨論的字典轉模型

字典轉模型可以說是有一個固定的模闆,使用它很簡單,但是我們應該從原理和思路上面去了解它,本文講述的是進行中最基本的plist檔案結構(還會有很多複雜的結構,不過都是建立在這個檔案結構之上)首先是一個大的Array,接着Array中包含了很多的Dictionary,在Dictionary中包含了很多的NSString對象。同時,本文的項目是Single-View模闆建立的。 首先先建立一個資料類(這裡以不同的國家為例子),命名為Country 1、首先我們從Country.m去分析:

#import "Student.h"
@implementation Student
- (instancetype)initWithDic:(NSDictionary *)dic
{
    if (self = [super init]) {
        // 不适用KVC的情況
        self.name = dic[@"name"];
        self.age = dic[@"school"];
        // 使用KVC的情況
        [self setValue:dic[@"name"] forKey:self.name];
        [self setValue:dic[@"school"] forKey:self.school];
        // 使用KVC的封裝好的字典操作方法
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}
+ (instancetype)statusWithDic:(NSDictionary *)dic
{
    return [[self alloc]initWithDic:dic];
}
// 在資料類中封裝好一個類方法,用于在其他類中(MVC中即為在Controller中)調用此方法來獲得模型化的資料對象
+ (NSArray *)students
{
    NSMutableArray *mutableArray = [NSMutableArray array];
    // 從plist檔案中拿到資料
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"statuses.plist" ofType:nil]];
    for (NSDictionary *dic in array) {
        // 取出的dic必須通過模型化再傳入到mutableArray中
        [mutableArray addObject:[self statusWithDic:dic]];
    }
    return mutableArray;
}
@end
           

2、接着是通過看.h檔案看看該怎麼提供接口,使得其他類更為友善地操作資料類

#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *school;

- (instancetype)initWithDic :(NSDictionary *)dic;
+ (instancetype)studentsWithDic :(NSDictionary *)dic;
+ (NSArray *)students;
@end
           

這裡面暴露了三個方法,其中前兩個方法都是關于初始化的方法,第三個方法是封裝好的獲得模型化的資料對象的方法接口 最後

3、最後我們看看怎麼去使用這個具有模型化的資料類,本文就在viewController類中進行使用說明

#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@property (copy , nonatomic) NSArray *students;
@end
@implementation ViewController
// 模型對象的懶加載
- (NSArray *)students
{
    if (_students == nil) {
       // 在這裡就調用了模型對象暴露出的接口,直接将模型化後的資料對象指派給了屬性
        _students = [Student students];
    }
    return _students;
}
           

4、以上操作做完了之後,我們就直接使用點文法,即為self.students來獲得模型化後的資料對象,然後通過self.student.name和self.student.age來獲得資料對象的屬性值