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

# encodeConditionalObject(_:)

An encoding method for subclasses to override to conditionally encode an object, preserving common references to it.

```
func encodeConditionalObject(_ object: Any?)
```

## Discussion

In the overriding method, `object` should be encoded only if it’s unconditionally encoded elsewhere (with any other `encode...Object:` method).

This method must be matched by a subsequent [`decodeObject()`](/documentation/Foundation/NSCoder/decodeObject()) message. Upon decoding, if `object` was never encoded unconditionally, `decodeObject` returns `nil` in place of `object`. However, if `object` was encoded unconditionally, all references to `object` must be resolved.

`NSCoder`’s implementation simply invokes [`encode(_:)`](/documentation/Foundation/NSCoder/encode(_:)-9648d).

## See Also

[`encodeConditionalObject(_:)`](/documentation/Foundation/NSArchiver/encodeConditionalObject(_:))

Conditionally archives a given object.



---

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)