<!--
{
  "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/encodeConditionalObject(_:forKey:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSCoder(im)encodeConditionalObject:forKey:"
  },
  "title" : "encodeConditionalObject(_:forKey:)"
}
-->

# encodeConditionalObject(_:forKey:)

An encoding method for subclasses to override to conditionally encode an object, preserving common references to it, only if it has been unconditionally encoded.

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

## Discussion

Subclasses must override this method if they support keyed coding.

The encoded object is decoded with the [`decodeObject(forKey:)`](/documentation/Foundation/NSCoder/decodeObject(forKey:)) method. If `objv` was never encoded unconditionally, [`decodeObject(forKey:)`](/documentation/Foundation/NSCoder/decodeObject(forKey:)) returns `nil` in place of `objv`.

---

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)