Command pattern is one of the most important and commonly used design patterns. It is originally described as a behavioral pattern in Design Patterns: Elements of Reusable Object-Oriented Software, Gamma et al.
A Command encapsulates requests in objects and uses a common interface to access those requests. It is much like a function object but more flexible, a Command can be created and sent from a client to a receiver and it can be executed at a later moment encapsulating for instance a method call.
The pattern can provide a kind of deferred execution mechanism.
A command must implement an interface that exposes at least the method Execute(), if we want to implement an Undo/Redo mechanism then an Unexecute() method must be provided. The Undo/Redo is also known as Memento Pattern which will be the argument of a future post.

Command Pattern UML diagram
Fig. 1 – Command Pattern UML diagram

Cocoa provides an off-the-shelf implementation of the command pattern, thus we can avoid to reinvent the wheel.
We need to use NSInvocation class from Foundation framework to set up a command and send it to another object, the receiver.
I must admit that NSInvocation setup is not so simple and quite tedious, we’ll see how to simplify tho process at the end of the post.
An example is worth a thousand words, so let’s start seeing a piece of code:

setArgument method accepts arguments to pass to the selector starting from index 2 and it is obviously strictly related to the signature of the selector.
I set up a project that shows how to enqueue commands in a NSMutableArray and how to execute them on a later time when the “Execute all commands” button is pressed.
In the example provided there is the addCommand method that can be used to reduce the amount of lines to initialize an NSInvocation over and over again.
Command Pattern Tutorial

Be Sociable, Share!