<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSCoder/encode(_:forKey:)-1mlmu",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSCoder(im)encodeObject:forKey:"
  },
  "title" : "encode(_:forKey:)"
}
-->

# encode(_:forKey:)

Encodes an object and associates it with the string key.

```
func encode(_ object: Any?, forKey key: String)
```

## Discussion

Subclasses must override this method to identify multiple encodings of `objv` and encode a reference to `objv` instead. For example, `NSKeyedArchiver` detects duplicate objects and encodes a reference to the original object rather than encode the same object twice.

## See Also

[`decodeObject(forKey:)`](/documentation/Foundation/NSCoder/decodeObject(forKey:))

Decodes and returns a previously-encoded object that was previously encoded with [`encode(_:forKey:)`](/documentation/Foundation/NSCoder/encode(_:forKey:)-1mlmu) or [`encodeConditionalObject(_:forKey:)`](/documentation/Foundation/NSCoder/encodeConditionalObject(_:forKey:)) and associated with the string `key`.



---

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)