直觀的做法是從 plist 讀出陣列,然後在 viewDidLoad 裡用 dict[@"icon"]、dict[@"name"] 取值。程式跑得動,但問題很明顯:
解法就是字典轉模型:把資料封裝進一個物件,讓控制器改和模型互動。
- (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;
這樣做的好處:
appInfo.name,有智慧提示、有型別檢查。模型 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;
逐行 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。