這個練習看起來簡單——一個換圖的小工具——但很適合拿來練「同一個需求,怎麼一步步寫得更好」。本文按四個階段推進:先跑通基本功能,再用字典取代 switch,接著引入懶加載,最後把資料抽到 plist 裡做到資料與程式碼分離。

做界面之前先想清楚兩件事,這習慣比寫程式碼本身更重要:
需要讀取或修改屬性的控件,要設成屬性:
需要監聽事件、加上監聽方法的物件:
另外還需要一個計數器變量 i,記錄目前顯示第幾張。
#define POTOIMGW 200
#define POTOIMGH 300
#define POTOIMGX 60
#define POTOIMGY 50
@interface YYViewController ()
// 變量宣告
@property (nonatomic, strong) UILabel *firstlab;
@property (nonatomic, strong) UILabel *lastlab;
@property (nonatomic, strong) UIImageView *icon;
@property (nonatomic, strong) UIButton *leftbtn;
@property (nonatomic, strong) UIButton *rightbtn;
@property (nonatomic, assign) int i;
- (void)change;
@end
@implementation YYViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.i = 0;
// 頂部序號標籤
UILabel *headlab = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 300, 30)];
headlab.textAlignment = NSTextAlignmentCenter;
headlab.textColor = [UIColor blackColor];
[self.view addSubview:headlab];
self.firstlab = headlab;
// 中間的圖片視圖
UIImageView *potoimg = [[UIImageView alloc] initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
potoimg.image = [UIImage imageNamed:@"biaoqingdi"];
[self.view addSubview:potoimg];
self.icon = potoimg;
// 底部描述標籤
UILabel *desclab = [[UILabel alloc] initWithFrame:CGRectMake(20, 400, 300, 30)];
desclab.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:desclab];
self.lastlab = desclab;
// 左方向鍵
UIButton *leftbtn = [UIButton buttonWithType:UIButtonTypeCustom];
leftbtn.frame = CGRectMake(0, self.view.center.y, 40, 40);
[leftbtn setBackgroundImage:[UIImage imageNamed:@"left_normal"] forState:UIControlStateNormal];
[leftbtn setBackgroundImage:[UIImage imageNamed:@"left_highlighted"] forState:UIControlStateHighlighted];
[self.view addSubview:leftbtn];
self.leftbtn = leftbtn;
[leftbtn addTarget:self action:@selector(leftclick:) forControlEvents:UIControlEventTouchUpInside];
// 右方向鍵
UIButton *rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
rightbtn.frame = CGRectMake(POTOIMGX + POTOIMGW + 10, self.view.center.y, 40, 40);
[rightbtn setBackgroundImage:[UIImage imageNamed:@"right_normal"] forState:UIControlStateNormal];
[rightbtn setBackgroundImage:[UIImage imageNamed:@"right_highlighted"] forState:UIControlStateHighlighted];
[self.view addSubview:rightbtn];
self.rightbtn = rightbtn;
[rightbtn addTarget:self action:@selector(rightclick:) forControlEvents:UIControlEventTouchUpInside];
// 初始化顯示
[self change];
}
- (void)change {
[self.firstlab setText:[NSString stringWithFormat:@"%d/5", self.i + 1]];
switch (self.i) {
case 0:
self.lastlab.text = @"什麼表情都弱爆了!";
self.icon.image = [UIImage imageNamed:@"biaoqingdi"];
break;
case 1:
self.lastlab.text = @"病例";
self.icon.image = [UIImage imageNamed:@"bingli"];
break;
case 2:
self.lastlab.text = @"王八";
self.icon.image = [UIImage imageNamed:@"wangba"];
break;
case 3:
self.lastlab.text = @"吃牛扒";
self.icon.image = [UIImage imageNamed:@"chiniupa"];
break;
case 4:
self.lastlab.text = @"蛋疼!";
self.icon.image = [UIImage imageNamed:@"danteng"];
break;
}
// 到頭之後禁用對應按鈕
self.leftbtn.enabled = (self.i != 0);
self.rightbtn.enabled = (self.i != 4);
}
- (void)rightclick:(UIButton *)btn {
self.i++;
[self change];
}
- (void)leftclick:(UIButton *)btn {
self.i--;
[self change];
}
@end
這版的問題很明顯:「序號」和「圖片」這兩份資料被硬寫進 switch 裡,兩者靠 case 順序隱式綁定。想加第六張圖,得回來改 switch;順序打亂就出錯。
觀察一下:每次換圖,本質上都是「同時取出兩個值」——圖片名和描述文字。既然這兩個值總是一起出現,那就該包成一個物件。字典是最快的做法。
- (void)change {
NSDictionary *dict1 = @{@"name": @"biaoqingdi", @"desc": @"什麼表情都弱爆了!"};
NSDictionary *dict2 = @{@"name": @"bingli", @"desc": @"病例"};
NSDictionary *dict3 = @{@"name": @"wangba", @"desc": @"烏龜"};
NSDictionary *dict4 = @{@"name": @"chiniupa", @"desc": @"吃牛扒"};
NSDictionary *dict5 = @{@"name": @"danteng", @"desc": @"蛋疼"};
NSArray *array = @[dict1, dict2, dict3, dict4, dict5];
self.icon.image = [UIImage imageNamed:array[self.i][@"name"]];
self.lastlab.text = array[self.i][@"desc"];
[self.firstlab setText:[NSString stringWithFormat:@"%d/5", self.i + 1]];
self.leftbtn.enabled = (self.i != 0);
self.rightbtn.enabled = (self.i != 4);
}
switch 沒了,資料結構也清楚了。但馬上會想到下一個問題:每次點擊都要重建一次字典和陣列,太浪費了。
直覺做法是把建立資料的程式碼搬到 viewDidLoad 裡,只跑一次。這可行,但缺點是對程式碼順序的要求極其嚴格——資料必須在第一次呼叫 change 之前準備好,兩段程式碼被時序綁死了,不夠穩健。
更好的做法是懶加載:需要的時候才建立,而「需要的時候」就是 getter 被呼叫的那一刻。
- (NSArray *)array {
NSLog(@"需要獲取數組");
if (_array == nil) {
NSLog(@"實例化數組");
NSDictionary *dict1 = @{@"name": @"biaoqingdi", @"desc": @"什麼表情都弱爆了!"};
NSDictionary *dict2 = @{@"name": @"bingli", @"desc": @"病例"};
NSDictionary *dict3 = @{@"name": @"wangba", @"desc": @"烏龜"};
NSDictionary *dict4 = @{@"name": @"chiniupa", @"desc": @"吃牛扒"};
NSDictionary *dict5 = @{@"name": @"danteng", @"desc": @"蛋疼"};
_array = @[dict1, dict2, dict3, dict4, dict5];
}
return _array;
}
只有第一次呼叫 getter 時 _array 為 nil,才會進去建立;之後一律直接回傳成員變量。「只執行一次」與「不需要順序約定」兩個好處同時拿到——這是懶加載比「寫在 viewDidLoad 裡」更受歡迎的原因。
順帶說明控件本身的懶加載寫法,注意屬性必須是 strong,否則物件會被提早釋放:
@property (nonatomic, strong) UIImageView *icon;
- (UIImageView *)icon {
if (!_icon) {
CGFloat imageW = 200;
CGFloat imageX = (320 - imageW) / 2;
CGFloat imageH = 200;
CGFloat imageY = 80;
_icon = [[UIImageView alloc] initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
[self.view addSubview:_icon];
}
return _icon;
}
到目前為止,資料仍然寫死在程式碼裡。真實專案中,這些內容很可能來自後端、來自配置檔,甚至需要運維隨時改。把資料搬到外面去,降低耦合,是這一步的目的。
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]; _array = [NSArray arrayWithContentsOfFile:path];
小提示:方法名裡出現 File 字眼的,參數通常要傳完整路徑,而不是檔名——arrayWithContentsOfFile: 就是典型例子。
放到 getter 裡:
- (NSArray *)array {
if (_array == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
_array = [[NSArray alloc] initWithContentsOfFile:path];
}
return _array;
}
而 change 方法從此不再關心資料從哪來:
- (void)change {
self.icon.image = [UIImage imageNamed:self.array[self.i][@"name"]];
self.lastlab.text = self.array[self.i][@"desc"];
[self.firstlab setText:[NSString stringWithFormat:@"%d/5", self.i + 1]];
self.leftbtn.enabled = (self.i != 0);
self.rightbtn.enabled = (self.i != 4);
}
plist 的結構如下:

執行結果:

開發思路的演進:
change 完成。三個容易忽略的注意點:
一個不到一百行的練習,把「資料建模 → 效能優化 → 關注點分離」三件事都走了一遍,值得反覆咀嚼。