命令模式(Command)把「一個請求或動作」封裝成物件。封裝之後,這個請求比原本的呼叫靈活得多:可以被傳遞、儲存、動態修改,或放進隊列延後執行。
Apple 在框架中是以 Target-Action 機制與 NSInvocation 來實作這個模式。NSInvocation 物件可以包含目標物件、方法選擇器與一組參數,並在需要時動態變更——這正是命令模式的教科書範例,它把「送出者」與「接收者」解耦,還能保存一整串請求。
在 ViewController 的類別延伸中加入兩個實例變數:
UIToolbar *toolbar;
// 用這個陣列當作堆疊,push/pop 各次操作以支援復原
NSMutableArray *undoStack;
於 viewDidLoad 建立工具列與堆疊:
toolbar = [[UIToolbar alloc] init];
UIBarButtonItem *undoItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemUndo
target:self
action:@selector(undoAction)];
undoItem.enabled = NO; // 堆疊為空時不可用
UIBarButtonItem *space = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil
action:nil];
UIBarButtonItem *delete = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemTrash
target:self
action:@selector(deleteAlbum)];
[toolbar setItems:@[undoItem, space, delete]];
[self.view addSubview:toolbar];
undoStack = [[NSMutableArray alloc] init];
注意工具列之所以不用座標初始化,是因為 viewDidLoad 時的 bounds 尚未是最終值。真正的位置要留到 viewWillLayoutSubviews:
- (void)viewWillLayoutSubviews {
toolbar.frame = CGRectMake(0, self.view.frame.size.height - 44,
self.view.frame.size.width, 44);
dataTable.frame = CGRectMake(0, 130,
self.view.frame.size.width,
self.view.frame.size.height - 200);
}
- (void)addAlbum:(Album *)album atIndex:(int)index {
[[LibraryAPI sharedInstance] addAlbum:album atIndex:index];
currentAlbumIndex = index;
[self reloadScroller];
}
刪除時,重點在於「先把反向操作存起來」:
- (void)deleteAlbum {
// 1
Album *deletedAlbum = allAlbums[currentAlbumIndex];
// 2
NSMethodSignature *sig = [self methodSignatureForSelector:@selector(addAlbum:atIndex:)];
NSInvocation *undoAction = [NSInvocation invocationWithMethodSignature:sig];
[undoAction setTarget:self];
[undoAction setSelector:@selector(addAlbum:atIndex:)];
[undoAction setArgument:&deletedAlbum atIndex:2];
[undoAction setArgument:¤tAlbumIndex atIndex:3];
[undoAction retainArguments];
// 3
[undoStack addObject:undoAction];
// 4
[[LibraryAPI sharedInstance] deleteAlbumAtIndex:currentAlbumIndex];
[self reloadScroller];
// 5
[toolbar.items[0] setEnabled:YES];
}
逐段解釋:
使用 NSInvocation 時有三個硬性規則:參數必須以指標傳遞;參數索引從 2 開始,索引 0 與 1 保留給 target 與 selector;若參數有機會被回收,記得呼叫 retainArguments。
- (void)undoAction {
if (undoStack.count > 0) {
NSInvocation *undoAction = [undoStack lastObject];
[undoStack removeLastObject];
[undoAction invoke];
}
if (undoStack.count == 0) {
[toolbar.items[0] setEnabled:NO];
}
}
復原就是「彈出」堆疊最後一個物件。這個物件必然是 NSInvocation,只要呼叫 invoke 就會重放當初記錄的請求,也就是把專輯加回列表。彈出後若堆疊已空,代表沒有更多可復原的操作,於是停用按鈕。
建置執行後可以順便驗證持久化:刪除一張專輯、把 App 送到背景、終止、重啟,若列表仍反映刪除結果,就代表存档流程也一併正常了。