ProtocolFoundation5.9.0
NSSecureCoding
Conforming to the NSSecureCoding
protocol indicates that an object handles encoding and decoding instances of itself in a manner that is robust against object substitution attacks.
protocol NSSecureCoding : NSCoding
Historically, many classes decoded instances of themselves like this:
if let object = decoder.decodeObject(forKey: "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 NSSecureCoding
:
An object that does not override
init(coder:)
can conform toNSSecureCoding
without any changes (assuming that it is a subclass of another class that conforms).An object that does override
init(coder:)
must decode any enclosed objects using thedecodeObject(of:forKey:)
method. For example:let obj = decoder.decodeObject(of: MyClass.self, forKey: "myKey")
In addition, the class must override its
NSSecureCoding
method to returntrue
.
Supertypes
protocol NSCoding
The
NSCoding
protocol declares the two methods that a class must implement so that instances of that class can be encoded and decoded. This capability provides the basis for archiving (where objects and other structures are stored on disk) and distribution (where objects are copied to different address spaces).