備忘錄模式(Memento)的目標是「在不破壞封裝的前提下,捕獲並還原物件的內部狀態」。也就是說,私有資料依然是私有的,外部只需要能存、能取,不必知道裡面長什麼樣子。
如果只需要保存一個數字(例如目前顯示的專輯索引),用 NSUserDefaults 就够了。在 ViewController 中實作兩個方法:
- (void)saveCurrentState {
// 使用者離開再回來時,期望看到一模一樣的畫面,
// 因此必須記下目前顯示的專輯。只有一筆資料,用 NSUserDefaults 即可。
[[NSUserDefaults standardUserDefaults] setInteger:currentAlbumIndex
forKey:@"currentAlbumIndex"];
}
- (void)loadPreviousState {
currentAlbumIndex = [[NSUserDefaults standardUserDefaults]
integerForKey:@"currentAlbumIndex"];
[self showDataForAlbumAtIndex:currentAlbumIndex];
}
在滑動視圖初始化之前先呼叫 [self loadPreviousState];,就能在啟動時還原上次的狀態。
只在啟動時讀取並沒有意義,關鍵是誰來觸發保存。當 App 進入背景時,系統會發送 UIApplicationDidEnterBackgroundNotification,正好可以當成存档時機。於 viewDidLoad 註冊觀察者:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(saveCurrentState)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
並且務必在 dealloc 中移除,避免通知中心持有已釋放物件:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
執行後你會發現一個有趣的現象:資料確實還原了,但滑動視圖仍停在第一頁。原因在於委派方法 initialViewIndexForHorizontalScroller: 尚未實作,於是起始索引永遠是 0。補上即可:
- (NSInteger)initialViewIndexForHorizontalScroller:(HorizontalScroller *)scroller {
return currentAlbumIndex;
}
若 PersistencyManager 中的專輯資料是寫死在程式碼裡,每次啟動都會重建,那只是假的持久化。理想做法是把物件列表寫進檔案。
直觀作法是逐個屬性寫入 plist,但這代表每新增一個類別(例如之後的 Movie)就得重寫一套存取程式碼;而且屬性若是私有,外部類別根本無法讀取。這正是 Apple 提供歸檔機制的理由。
先讓 Album 類別符合 NSCoding 協議:
@interface Album : NSObject <NSCoding>
接著實作編碼與解碼:
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.year forKey:@"year"];
[aCoder encodeObject:self.title forKey:@"album"];
[aCoder encodeObject:self.artist forKey:@"artist"];
[aCoder encodeObject:self.coverUrl forKey:@"cover_url"];
[aCoder encodeObject:self.genre forKey:@"genre"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
_year = [aDecoder decodeObjectForKey:@"year"];
_title = [aDecoder decodeObjectForKey:@"album"];
_artist = [aDecoder decodeObjectForKey:@"artist"];
_coverUrl = [aDecoder decodeObjectForKey:@"cover_url"];
_genre = [aDecoder decodeObjectForKey:@"genre"];
}
return self;
}
encodeWithCoder: 在存档時呼叫,initWithCoder: 在還原時呼叫。寫起來簡單,卻能把私有狀態完整保留。
在 PersistencyManager.h 宣告 - (void)saveAlbums;,並於實作檔加入:
- (void)saveAlbums {
NSString *filename = [NSHomeDirectory() stringByAppendingString:@"/Documents/albums.bin"];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:albums];
[data writeToFile:filename atomically:YES];
}
當被歸檔的物件內含其他物件時,歸檔器會自動遞迴處理子物件。此例中 albums 是 Album 的陣列,由於陣列與 Album 都支援 NSCoding,裡面的每一項都會被寫入。
而在 init 中則反向操作:
- (id)init {
self = [super init];
if (self) {
NSData *data = [NSData dataWithContentsOfFile:
[NSHomeDirectory() stringByAppendingString:@"/Documents/albums.bin"]];
albums = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (albums == nil) {
albums = [NSMutableArray arrayWithArray:@[
[[Album alloc] initWithTitle:@"Best of Bowie" artist:@"David Bowie" coverUrl:@"https://www.coversproject.com/static/thumbs/album/album_david%20bowie_best%20of%20bowie.png" year:@"1992"],
[[Album alloc] initWithTitle:@"It's My Life" artist:@"No Doubt" coverUrl:@"https://www.coversproject.com/static/thumbs/album/album_no%20doubt_its%20my%20life%20%20bathwater.png" year:@"2003"],
[[Album alloc] initWithTitle:@"Nothing Like The Sun" artist:@"Sting" coverUrl:@"https://www.coversproject.com/static/thumbs/album/album_sting_nothing%20like%20the%20sun.png" year:@"1999"],
[[Album alloc] initWithTitle:@"Staring at the Sun" artist:@"U2" coverUrl:@"https://www.coversproject.com/static/thumbs/album/album_u2_staring%20at%20the%20sun.png" year:@"2000"],
[[Album alloc] initWithTitle:@"American Pie" artist:@"Madonna" coverUrl:@"https://www.coversproject.com/static/thumbs/album/album_madonna_american%20pie.png" year:@"2000"]
]];
[self saveAlbums];
}
}
return self;
}
檔案存在就還原,不存在就用預設資料建立並立即存檔,等下次啟動即可讀取。
App 的所有服務都經過 LibraryAPI,因此保存動作也應該由它轉發。於 LibraryAPI.h 宣告:
- (void)saveAlbums;
實作:
- (void)saveAlbums {
[persistencyManager saveAlbums];
}
如此一來,每當 ViewController 保存自身狀態時,LibraryAPI 便會觸發持久化流程。
驗證成果並不容易,因為沒有簡單 API 能檢查存档是否正確。實務上可以到 Finder 查看模擬器的 Documents 目錄,確認 albums.bin 是否產生;若要確認「有沒有真的存進去」,最直接的辦法就是加上刪除功能,刪掉一筆、重啟 App,看列表是否反映了變更。順帶一提,刪除操作最好再配上「復原」選項,誤刪時才有救——而這正好引出了下一篇的命令模式。