Instance Method




- (void)registerUndoWithTarget:(id)target selector:(SEL)selector object:(id)anObject;



The target of the undo operation.

The undo manager maintains an unowned reference to target to prevent retain cycles.


The selector for the undo operation.


The argument sent with the selector.

The undo manager maintains a strong reference to anObject.


Use registerUndoWithTarget:selector:object: to register a selector for an undo operation. To register a selector on the undo stack, you also need to make the method available to the Objective-C runtime by applying the @objc attribute to the method. For more on how to create a selector, see Selectors.

Calling this method also clears the redo stack.

The following example demonstrates how to register and use a selector on the undo stack by modeling a Garden class with two methods: plant(flower:) and pluck(flower:). The plant(flower:) method removes a flower from the garden while pluck(flower:) adds a flower such that effectively, the two methods are inverse operations of each other. This inverse quality makes it ideal to register plant(flower:) and pluck(flower:) to be each other's undo operation.

class Garden {
    typealias FlowerName = String

    var flowers: [FlowerName: Int]
    var manager = UndoManager()

    init(flowers: [FlowerName: Int]) { = flowers
    @objc func plant(flower: FlowerName) {
        flowers[flower, default: 0] += 1
        manager.registerUndo(withTarget: self, selector: #selector(pluck), object: flower)
    @objc func pluck(flower: FlowerName) {
        flowers[flower, default: 0] -= 1
        manager.registerUndo(withTarget: self, selector: #selector(plant), object: flower)
var garden = Garden(flowers: ["orchid" : 2, "lavender": 1, "violet": 2])
garden.pluck(flower: "orchid")
// == ["orchid" : 1, "lavender": 1, "violet": 2]
// == ["orchid" : 2, "lavender": 1, "violet": 2]

See Also

Registering Undo Operations

- registerUndoWithTarget:handler:

Records a single undo operation for a given target so that when an undo is performed, it executes the specified block.

- prepareWithInvocationTarget:


Beta Software


Learn more about using Apple's beta software