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

# write(to:ofType:)

Writes the contents of the document to a file or file package located by a URL, that is formatted to a specified type.

```
nonisolated func write(to url: URL, ofType typeName: String) throws
```

## Parameters

`url`

The location to which the document contents are written.

`typeName`

The string that identifies the document type.

## Discussion

The default implementation of this method just invokes `[self fileWrapperOfType:typeName error:outError]` and writes the returned file wrapper to disk.

For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes `[self writeToFile:[absoluteURL path] ofType:typeName]` if [`writeToFile:ofType:`](/documentation/AppKit/NSDocument/writeToFile:ofType:) is overridden and the URL uses the `file:` scheme.

> 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)