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

# data(ofType:)

Creates and returns a data object that contains the contents of the document, formatted to a specified type.

```
func data(ofType typeName: String) throws -> Data
```

## Parameters

`typeName`

The string that identifies the document type.

## Return Value

A data object containing the document contents, or, if the data object could not be created, `nil`.

## Discussion

The default implementation of this method throws an exception because at least one of the writing methods (this method, [`write(to:ofType:)`](/documentation/AppKit/NSDocument/write(to:ofType:)), [`fileWrapper(ofType:)`](/documentation/AppKit/NSDocument/fileWrapper(ofType:)), or [`write(to:ofType:for:originalContentsURL:)`](/documentation/AppKit/NSDocument/write(to:ofType:for:originalContentsURL:))) must be overridden.

For backward binary compatibility with OS X v10.3 and earlier, the default implementation of this method instead invokes `dataRepresentationOfType:``typeName` on `self` if `dataRepresentationOfType:` is overridden.

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