<!--
{
  "availability" : [
    "macOS: 10.7.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "AppKit",
  "identifier" : "/documentation/AppKit/NSDocument/duplicate()",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "AppKit"
    ],
    "preciseIdentifier" : "c:objc(cs)NSDocument(im)duplicateAndReturnError:"
  },
  "title" : "duplicate()"
}
-->

# duplicate()

Creates a new document whose contents are the same as the receiver and returns an error object if unsuccessful.

```
func duplicate() throws -> NSDocument
```

## Return Value

The new document if duplication is successful; otherwise `nil`.

## Discussion

The new document returned doesn’t yet have a value to return from [`fileURL`](/documentation/AppKit/NSDocument/fileURL).

The default implementation of this method first uses [`writeSafely(to:ofType:for:)`](/documentation/AppKit/NSDocument/writeSafely(to:ofType:for:)) to write the document’s current contents to a file located in the same directory that is used for the autosaved contents of untitled documents and with the same sort of name, then invokes `[[NSDocumentController sharedDocumentController] duplicateDocumentWithContentsOfURL:newContentsURL copying:NO displayName:aDisplayName error:outError]`.

You can override this method to customize what is done during document duplication, but if your override does not invoke `[NSDocumentController duplicateDocumentWithContentsOfURL:copying:displayName:error:]` you must take care to do things that that method does, especially invoking `[NSDocumentController addDocument:]` and `[NSFileCoordinator addFilePresenter:]`.

> Handling Errors in Swift:
> In Swift, this method is marked with the `throws` keyword to indicate that it throws an error in cases of failure.
> 
> When overriding this method, use the `throw` statement to throw an `NSError`, as described in [Error Handling](https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html) in [The Swift Programming Language](https://docs.swift.org/swift-book/) and `About Imported Cocoa Error Parameters`.

---

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)