<!--
{
  "availability" : [
    "iOS: 9.0.0 -",
    "iPadOS: 9.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.11.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/UndoManager/registerUndo(withTarget:handler:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "s:So13NSUndoManagerC10FoundationE12registerUndo10withTarget7handleryx_yxctRlzClF"
  },
  "title" : "registerUndo(withTarget:handler:)"
}
-->

# registerUndo(withTarget:handler:)

Registers the specified closure to implement a single undo operation that the target receives.

```
@MainActor @preconcurrency func registerUndo<TargetType>(withTarget target: TargetType, handler: @escaping @MainActor (TargetType) -> Void) where TargetType : AnyObject
```

## Parameters

`target`

The target of the undo operation.

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

`handler`

A closure to execute when an operation is undone.

    The closure takes a single argument, the target of the undo operation.

## Discussion

Use [`registerUndo(withTarget:handler:)`](/documentation/Foundation/UndoManager/registerUndo(withTarget:handler:)) to register a closure as an undo operation on the undo stack. The registered closure is then executed when `undo` is called and the undo operation occurs. The target needs to be a reference type so that its state can be undone or redone by the undo manager.

The following example demonstrates how you can use this method to register an undo operation that adds an element back into a mutable array.

```swift
var manager = UndoManager()
var bouquetSelection: NSMutableArray = ["lilac", "lavender"]
func pull(flower: String) {
    bouquetSelection.remove(flower)
    manager.registerUndo(withTarget: bouquetSelection) { $0.add(flower) }
}
pull(flower: "lilac")
// bouquetSelection == ["lavender"]
manager.undo()
// bouquetSelection == ["lavender", "lilac"]
```

To avoid retain cycles with the target, operate on the closure parameter rather than on variables in an outer scope that reference the same target. For example, in the code listing above, the closure operates on the `$0` parameter rather than directly on `bouquetSelection`.

## See Also

  [Introduction to Undo Architecture](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UndoArchitecture/UndoArchitecture.html#//apple_ref/doc/uid/10000010)



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)