How iOS Implements Undo/Redo with Command & Observer Patterns
This article explains how iOS keyboards achieve undo and redo functionality by combining the Command and Observer design patterns, illustrates their class structures, and shows how the NSUndoManager leverages these patterns to manage undo and redo stacks in Cocoa Touch applications.
Current keyboards—both system‑provided and third‑party—offer undo and redo features. Do you know which design patterns power them? They rely on the Command pattern together with the Observer pattern .
Simple Introduction
What is the Command (Command) pattern?
The Command pattern is a behavioral design pattern that encapsulates an operation, method call, or command into an object, which can be executed at an appropriate time.
Pattern type: Behavioral pattern
Definition: Encapsulate a request as an object.
Typical scenario: Like a guard ready to act on command—e.g., a menu button that triggers a specific action when clicked.
Class diagram:
The invoker holds a composite command class, and the command class references the command receiver.
What is the Observer (Observer) pattern?
Pattern type: Behavioral pattern
Definition: Defines a one‑to‑many relationship where a change in the subject (observable) automatically notifies observers, allowing them to update their state.
Typical scenario: Controllers observe model properties; when a property changes, the view updates. Keyboard input is observed and then displayed.
Class diagram:
The observable holds references to its observers.
Real‑World Use in the Cocoa Touch Framework
Apple provides NSUndoManager for undo/redo management, which consists of three main components:
Redo stack
Undo stack
Command object:
NSInvocationWhen entering the undo stack, NSInvocation executes the undo command; when entering the redo stack, it executes the redo command.
To combine these patterns in your own implementation:
Add an NSInvocation execution object to the Command.
Include an observer list in the Command so that executing a command notifies its observers.
Create a manager class similar to NSUndoManager to handle the overall command list.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
