App 會經歷多種狀態,其中最單純的一組轉換是:活動(Active)→ 不活動(Inactive)→ 回到活動。不活動通常發生在來電、跳出系統提示、或即將被切到背景之前。適時處理這段空檔,能避免動畫在背景裡空轉、也能在使用者回來時把狀態接回來。
#import "ZYViewController.h"
@interface ZYViewController ()
@end
@implementation ZYViewController
@synthesize label;
@synthesize animate;
- (void)viewDidLoad
{
[super viewDidLoad];
// 註冊兩個通知,用來感知狀態切換
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:[UIApplication sharedApplication]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:[UIApplication sharedApplication]];
// 建立一個置中的大標籤
CGRect bounds = self.view.bounds;
CGRect labelFrame = CGRectMake(bounds.origin.x,
CGRectGetMidY(bounds) - 50,
bounds.size.width,
100);
self.label = [[UILabel alloc] initWithFrame:labelFrame];
self.label.font = [UIFont fontWithName:@"Helvetica" size:70];
self.label.text = @"Archy!";
self.label.textAlignment = NSTextAlignmentCenter;
self.label.backgroundColor = [UIColor clearColor];
[self.view addSubview:self.label];
}
- (void)dealloc
{
[label release];
// 觀察者有始有終:一定要移除,否則釋放後收到通知會 crash
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
// 讓標籤旋轉到 180 度
- (void)rotateLabelDown
{
// 隱式動畫:Core Animation 會把屬性從目前值平滑過渡到指定值
[UIView animateWithDuration:0.5
animations:^{
// transform 的旋轉以弧度為單位
self.label.transform = CGAffineTransformMakeRotation(M_PI);
}
completion:^(BOOL finished) {
// 完成後呼叫另一個方法,形成來回擺動
[self rotateLabelUp];
}];
}
// 讓標籤轉回 0 度
- (void)rotateLabelUp
{
[UIView animateWithDuration:0.5
animations:^{
self.label.transform = CGAffineTransformMakeRotation(0);
}
completion:^(BOOL finished) {
// 只有仍在活動狀態時才繼續下一輪
if (animate)
[self rotateLabelDown];
}];
}
// App 即將變成不活動
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"%@", NSStringFromSelector(_cmd));
animate = NO; // 停止動畫迴圈
}
// App 恢復活動
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"%@", NSStringFromSelector(_cmd));
animate = YES; // 恢復動畫
[self rotateLabelDown];
}
@end
這是整個範例的關鍵。動畫是一組「A 完成後呼叫 B、B 完成後再呼叫 A」的循環,如果沒有中斷條件,它就會永遠跑下去。
問題在於:App 進入不活動狀態時,這個循環並不會自動停下。若不做處理,動畫會在背景裡繼續消耗資源,回到前景時還可能出現狀態錯亂(例如 label 卡在旋轉中途)。
解法是用 animate 旗標作為迴圈閘門:在 applicationWillResignActive: 中設為 NO,讓下一次 completion 檢查時停止續接;回到活動狀態時設回 YES 並重新啟動動畫。這樣動畫的生命週期就跟著 App 的狀態一起呼吸。
App 啟動後標籤開始來回旋轉:

啟動時的 console 輸出:
2013-06-08 13:20:24.265 State Lab[414:c07] application:didFinishLaunchingWithOptions: 2013-06-08 13:20:24.287 State Lab[414:c07] applicationDidBecomeActive:
按下 Home 鍵之後:
2013-06-08 13:21:57.394 State Lab[414:c07] applicationWillResignActive: 2013-06-08 13:21:57.396 State Lab[414:c07] applicationDidEnterBackground:
再次開啟 App:

2013-06-08 13:22:44.051 State Lab[414:c07] applicationWillEnterForeground: 2013-06-08 13:22:44.052 State Lab[414:c07] applicationDidBecomeActive:
把這些通知放回完整的生命週期來看會更清楚:
· Not Running:尚未啟動或已被終止。
· Inactive:正在運行但未收到事件,例如來電、控制中心被拉出、系統提示跳出。此時應該停止動畫與不必要的運算。
· Active:正常運行、可接收使用者輸入。
· Background:已不在畫面上,仍可短暫執行以完成收尾工作(存檔、上傳)。
· Suspended:被系統凍結,記憶體可能被回收。
對應的 AppDelegate 方法有五個:application:didFinishLaunchingWithOptions:、applicationWillResignActive:、applicationDidBecomeActive:、applicationDidEnterBackground:、applicationWillEnterForeground:。
一個實務上的判斷原則:短暫中斷(來電、通知)用 Active/Inactive 配對處理;長時間離開(切換 App、鎖機)用 Background/Foreground 配對處理。把動畫、計時器放在前者,把資料存檔、連線釋放放在後者,責任劃分會清楚很多。
此外别忘了在 dealloc 中呼叫 removeObserver:。這是 notification 相關 crash 最常見的原因,在現代以 Block 為基礎的 addObserverForName:object:queue:usingBlock: 寫法中,則要記得保存回傳的 observer token 並在合適時移除。