A protocol that enables encoding and decoding in a manner that is robust against object substitution attacks.
SDKs
- iOS 6.0+
- macOS 10.8+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
protocol NSSecureCoding
Overview
Historically, many classes decoded instances of themselves like this:
if let object = decoder.decodeObjectForKey("myKey") as MyClass {
// ...succeeds...
} else {
// ...fail...
}
This technique is potentially unsafe because by the time you can verify the class type, the object has already been constructed, and if this is part of a collection class, potentially inserted into an object graph.
In order to conform to NSSecure:
An object that does not override
init(coder:)can conform toNSSecurewithout any changes (assuming that it is a subclass of another class that conforms).Coding An object that does override
init(coder:)must decode any enclosed objects using thedecodemethod. For example:Object Of Class: for Key: let obj = decoder.decodeObject(of:MyClass.self, forKey: "myKey")In addition, the class must override the getter for its
supportsproperty to returnSecure Coding true.
For more information about how this relates to the NSXPC API, see Creating XPC Services in Daemons and Services Programming Guide.

