前言
最近項目需求加上狀態恢復, 記得之前在書上看過, 這次單獨抽出這個功能實現詳細梳理一下, 方便自己溫習一下, 也方便不知道的 developer 學習.
狀態恢復?
舉個栗子:
在使用名字為 A 的 app 時, 從列表頁面進入詳情頁面, 這時你不想看了, 點擊 Home 鍵, 回到后臺, 打開 B 開始玩. 過了一段時間之后, 由于 A 沒有寫后臺運行的功能, 這時, 系統會關閉 A, 再打開時, 你看到的是之前進入的詳情頁面.
系統一點的話說就是, 系統在進入后臺時會保存 app 的層次結構, 在下一次進入的時候會恢復這個結構中所有的 controller. 系統在終止之前會遍歷結構中每一個節點, 恢復標識, 類, 保存的數據. 在終止應用之后, 系統會把這些信息存儲在系統文件中.
恢復標識
一般和對象的類名相同, 其類被稱為恢復類.
實現
下面通過一個 demo 演示狀態恢復的實現, 這個 demo 是一個保存聯系人信息的 demo. 以下代碼以 demo 中控制器為例. 建議 demo 和本文一起看, 更好理解.
1. 開啟
默認情況下, app 的狀態恢復是關閉的, 需要我們手動開啟.
在 AppDelegate.m 中手動打開:
#pragma mark - open state restoration
// 和NSCoding協議方法有點像, encode, decode
- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder {
return YES;
}
- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {
return YES;
}
系統在保存 app 狀態時, 會先從 root VC 去查詢是否有restorationIdentifier
屬性, 如果有, 則保存狀態, 繼續查詢其子控制器, 有則保存. 直到找不到帶有restorationIdentifier
的子控制器, 系統會停止保存其與其子控制器的狀態.
畫個圖解釋一下:
上圖三級 VC 即使有restorationIdentifier
也不會恢復.
application:willFinishLaunchingWithOptions:
方法會在啟用狀態恢復之前調用, 我們需要將觸發啟用方法之前的代碼寫在這個方法中.
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] init];
self.window.frame = [UIScreen mainScreen].bounds;
self.window.backgroundColor = [UIColor whiteColor];
return YES;
}
然后為根視圖控制器添加恢復標識:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 如果沒有觸發恢復, 則重新設置根控制器
if (!self.window.rootViewController) {
YNMainTableController *table = [[YNMainTableController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:table];
nav.restorationIdentifier = NSStringFromClass([nav class]);
self.window.rootViewController = nav;
}
[self.window makeKeyAndVisible];
return YES;
}
2. 為子控制器實現
a. 設置恢復標識和恢復類
在一級控制器初始化方法中為其設置:
#pragma mark - initial
- (instancetype)init {
self = [super init];
if (self) {
// 設置恢復標識和恢復類
self.restorationIdentifier = NSStringFromClass([self class]);
self.restorationClass = [self class];
}
return self;
}
在子控制器中設置:
- (instancetype)initWithNewItem:(BOOL)isNew {
self = [super initWithNibName:nil bundle:nil];
if (self) {
// 設置恢復類和恢復標識
self.restorationIdentifier = NSStringFromClass([self class]);
self.restorationClass = [self class];
if (isNew) {
UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(save:)];
self.navigationItem.rightBarButtonItem = doneItem;
UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancel:)];
self.navigationItem.leftBarButtonItem = cancelItem;
}
}
return self;
}
如果是模態推出帶有navigationController
的控制器, 需要為這個 nav 設置恢復標識:
- (void)addNewItem:(id)sender {
YNCustomItem *item = [[YNItemHandler sharedStore] createItem];
YNSonViewController *sonVC = [YNSonViewController newItem:YES];
sonVC.item = item;
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:sonVC];
// 為 UINavigationController 設置恢復類
nav.restorationIdentifier = NSStringFromClass([nav class]);
[self presentViewController:nav animated:YES completion:nil];
}
b. 遵循恢復協議
需要狀態恢復的控制器需要遵循<UIViewControllerRestoration>
協議:
一級視圖控制器中:
#pragma mark - view controller restoration
+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
return [[self alloc] init];
}
同樣, 二級視圖控制器中, demo 中添加新聯系人信息和查看聯系人信息調用的是同一個控制器, 初始化方法為自己封裝的方法newItem:(BOOL)isNew
, isNew 為 NO 時, 查看聯系人, 為 YES 時, 新建聯系人. 此時有兩種情況:
-
新建聯系人:
在恢復狀態時
newItem:(BOOL)isNew
參數傳入 YES -
查看聯系人:
參數傳入 NO
那么如何判斷傳入什么參數呢? 通過
+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder;
方法中的identifierComponents
來判斷, identifierComponents
存儲了當前視圖控制器及其所有上級視圖控制器的恢復標識. 那么現在我們來看一下:
- 新建聯系人程序中的恢復標識有:
- root VC 的 nav 恢復標識
- 二級 VC 的 nav 恢復標識(沒有一級 VC 的標識是因為 二級 VC 是由一級 VC 的 nav 模態出來的)
- 二級 VC 自身的恢復標識
- 查看聯系人的恢復標識有:
- 根 VC 的 nav 恢復標識
- 二級 VC 自身的恢復標識(沒有一級的和上面同理)
所以新建聯系人的 VC 的identifierComponents
的個數為3, 查看聯系人的為2個. 那么則可以判斷參數如何傳遞:
#pragma mark - view controller restoration
+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
BOOL isNew = NO;
if (identifierComponents.count == 3) {
isNew = YES;
}
return [[self alloc] initWithNewItem:isNew];
}
c. 為 nav 設置恢復類
// 如果某個對象沒有設置恢復類, 那么系統會通過 AppDelegate 來創建
- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
UINavigationController *nav = [[UINavigationController alloc] init];
// 恢復標識路徑中最后一個對象就是 nav 的恢復標識
nav.restorationIdentifier = [identifierComponents lastObject];
if (identifierComponents.count == 1) {
self.window.rootViewController = nav;
}
return nav;
}
至此, 控制器的狀態恢復已完成, 但是現實的數據還需要做持久化處理, 否則只是恢復了一個沒有數據的控制器.
d. 數據持久化
使二級頁面詳情頁需要的數據保存:
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
[coder encodeObject:self.item.itemKey forKey:kRestorationKey];
// 保存 textField 中的文本, 以便恢復更改后的文本
self.item.name = self.nameField.text;
self.item.phoneNumber = [self.phoneField.text integerValue];
self.item.sex = self.sexField.text;
// 存入本地
[[YNItemHandler sharedStore] saveItems];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
NSString *itemKey = [coder decodeObjectForKey:kRestorationKey];
for (YNCustomItem *item in [[YNItemHandler sharedStore] allItems]) {
if ([item.itemKey isEqualToString:itemKey]) {
self.item = item;
NSLog(@"name:%@, phone:%ld, sex:%@", self.item.name, self.item.phoneNumber, self.item.sex);
break;
}
}
[super decodeRestorableStateWithCoder:coder];
}
二級頁面狀態恢復完成, 這時候測試(測試方法: 運行后, cmd + shift + h回到桌面, Xcode停止運行, 然后再運行), 重新打開項目, 發現視圖控制器狀態是恢復了, 但是數據還是空白. 然后打上斷點看了下周期, 把數據獲取方法寫在viewWillAppear:
里就好了.
e. 記錄 tableview 狀態
為一級 VC 設置其 tableView 的恢復標識:
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"State Restoration";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewItem:)];
[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YNTableViewCell class]) bundle:nil] forCellReuseIdentifier:kCellIdentifier];
// 給 tableView 設置恢復標識, tableView 自動保存的 contentOffset 會恢復其滾動位置
self.tableView.restorationIdentifier = kTableViewIdentifier;
}
記錄 tableView 是否處于 editing 狀態:
// 記錄 tableView 是否處于編輯狀態
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder {
[coder encodeBool:self.isEditing forKey:kTableViewEditingKey];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder {
self.editing = [coder decodeBoolForKey:kTableViewEditingKey];
[super decodeRestorableStateWithCoder:coder];
}
通過<UIDataSourceModelAssociation>
協議使視圖對象在恢復時關聯正確的 model 對象. 當保存狀態時, 其會根據 indexPath 保存一個唯一標識.
實現<UIDataSourceModelAssociation>
協議方法:
- (NSString *)modelIdentifierForElementAtIndexPath:(NSIndexPath *)idx inView:(UIView *)view {
NSString *identifier = nil;
if (idx && view) {
YNCustomItem *item = [[YNItemHandler sharedStore] allItems][idx.row];
identifier = item.itemKey;
}
return identifier;
}
- (NSIndexPath *)indexPathForElementWithModelIdentifier:(NSString *)identifier inView:(UIView *)view {
NSIndexPath *indexPath = nil;
if (identifier && view) {
for (YNCustomItem *item in [[YNItemHandler sharedStore] allItems]) {
if ([identifier isEqualToString:item.itemKey]) {
NSInteger row = [[[YNItemHandler sharedStore] allItems] indexOfObjectIdenticalTo:item];
indexPath = [NSIndexPath indexPathForRow:row inSection:0];
break;
}
}
}
return indexPath;
}
最后記得在進入后臺前持久化當前的 item(實際開發中記得用 cache(項目里使用 YYCache) 或者 db(項目里使用 FMDB) 去即時持久化視圖數據, 是一個比較穩妥的方案):
- (void)applicationDidEnterBackground:(UIApplication *)application {
BOOL success = [[YNItemHandler sharedStore] saveItems];
if (success) {
NSLog(@"成功保存所有項目");
} else {
NSLog(@"保存項目失敗");
}
}
至此, 狀態恢復基本使用已經實現.
測試
- 添加 n 個新的聯系人, 滑動列表到測試位置, 讓 tableView 進入到編輯狀態. 按下
cmd + shift + h
進入 home, 用 Xcode 結束程序cmd+.
, 再次運行看看是否在最后滑動位置, 或者是否處于編輯狀態. - 恢復編輯狀態, 隨便進入一個聯系人詳情, 重復上面的操作, 看看進入程序之后是否處于上次退出前的詳情頁面.
最后, 可能說的有些模糊, 還是結合demo看要更明白點.