您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

字典轉模型(Dictionary → Model)觀念、寫法與 KVC 優化

編輯:iOS 開發綜合

問題:控制器不該直接跟 plist 打交道

直觀的做法是從 plist 讀出陣列,然後在 viewDidLoad 裡用 dict[@"icon"]、dict[@"name"] 取值。程式跑得動,但問題很明顯:

  • 字串 key 沒有智慧提示,全靠手打。
  • key 打錯時編譯器不會報錯,只會靜靜地取到 nil。
  • 同一個 key 散落在多處,一旦欄位改名就得逐處搜尋。

解法就是字典轉模型:把資料封裝進一個物件,讓控制器改和模型互動。

「問題程式碼」長這樣

- (NSArray *)appList
{
    if (!_appList) {
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
        _appList = [NSArray arrayWithContentsOfFile:path];
    }
    return _appList;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    int totalCol = 3;
    CGFloat viewW = 80, viewH = 90;
    CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
    CGFloat marginY = 10, startY = 20;

    for (int i = 0; i < self.appList.count; i++) {
        int row = i / totalCol;
        int col = i % totalCol;
        CGFloat x = marginX + (viewW + marginX) * col;
        CGFloat y = startY + marginY + (viewH + marginY) * row;

        UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];
        [self.view addSubview:appView];

        NSDictionary *dict = self.appList[i];
        imageView.image = [UIImage imageNamed:dict[@"icon"]];  // ← 手打 key,容易出錯
        label.text      = dict[@"name"];                       // ← 同上
    }
}

字典轉模型的核心約定

模型必須提供一個能接收字典的建構方法:

- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)xxxWithDict:(NSDictionary *)dict;

這樣做的好處:

  1. 降低耦合度——控制器不再依賴資料的具體結構。
  2. 錯誤集中——所有 key 對應關係只寫一次,出錯只需改一處。
  3. 編碼效率——後續直接用 appInfo.name,有智慧提示、有型別檢查。
  4. 封裝內部細節——呼叫方不必知道資料從哪來、怎麼處理。

實作一:基礎版本

模型 LFAppInfo.h

#import <Foundation/Foundation.h>

@interface LFAppInfo : NSObject
// 應用程式名稱
@property (nonatomic, copy) NSString *name;
// 應用程式圖示名稱
@property (nonatomic, copy) NSString *icon;
// 圖像:readonly 只產生 getter,不產生帶底線的實例變數
@property (nonatomic, strong, readonly) UIImage *image;

// instancetype 會讓編譯器檢查實例化後的型別是否正確
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 工廠方法 */
+ (instancetype)appInfoWithDict:(NSDictionary *)dict;
@end

模型 LFAppInfo.m

#import "LFAppInfo.h"

@interface LFAppInfo ()
{
    UIImage *_imageABC;
}
@end

@implementation LFAppInfo

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
    }
    return self;
}

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

// 遲到的載入:真正被用到時才解碼圖片
- (UIImage *)image
{
    if (!_imageABC) {
        _imageABC = [UIImage imageNamed:self.icon];
    }
    return _imageABC;
}

@end

控制器改成這樣

- (NSArray *)appList
{
    if (!_appList) {
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];

        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            [arrayM addObject:[LFAppInfo appInfoWithDict:dict]];
        }
        _appList = arrayM;
    }
    return _appList;
}

// 使用處
LFAppInfo *appInfo = self.appList[i];
imageView.image = appInfo.image;
label.text      = appInfo.name;

實作二:KVC 讓程式碼再短一截

逐行 self.xxx = dict[@"xxx"] 寫多了仍然單調。Cocoa 提供了鍵值編碼(Key-Value Coding),可以間接設定屬性:

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        [self setValue:dict[@"answer"] forKeyPath:@"answer"];
        [self setValue:dict[@"icon"]   forKeyPath:@"icon"];
        [self setValue:dict[@"title"]  forKeyPath:@"title"];
        [self setValue:dict[@"options"]forKeyPath:@"options"];
    }
    return self;
}

而這一段又能進一步濃縮成一行:

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        // 屬性必須在字典中都存在:可以多,但不能少
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

使用 KVC 的前提:類別的屬性名稱必須與字典的 key 完全一致。若不一致,就得實作 setValue:forUndefinedKey: 攔截,或改用 MJExtension、YYModel 這類第三方框架做型別轉換與 key 映射。

再進一步:把讀檔也搬進模型

// LFQuestion.h
+ (NSArray *)questions;
// LFQuestion.m
+ (NSArray *)questions
{
    NSArray *array = [NSArray arrayWithContentsOfFile:
        [[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];

    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        [arrayM addObject:[LFQuestion questionWithDict:dict]];
    }
    return arrayM;
}
// 控制器
- (NSArray *)questions
{
    if (!_questions) {
        _questions = [LFQuestion questions];
    }
    return _questions;
}

三個補充知識點

readonly 屬性:不允許修改指標位址,但物件本身的屬性仍可變。它只產生 getter,不產生帶底線的實例變數,因此實作 getter 時要自己宣告 ivar(如範例中的 _imageABC)。合理運用 readonly 能進一步降低耦合。

instancetype 的意義:編譯器會依它檢查「實例化後的型別是否正確」,比 id 安全。此外子類別呼叫時會回傳正確的子類別型別,而 id 不會。

instancetype 與 id 的差異:兩者都能表示任意物件型別,但 instancetype 只能用於回傳值,不能當參數,而且多了一層編譯期型別檢查。結論很明確:新專案一律用 instancetype。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved