Mac Developer Library

Developer

Foundation Framework Reference NSSecureCoding Protocol Reference

Options
Deployment Target:

On This Page
Language:

NSSecureCoding

Inheritance


Not Applicable

Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in OS X v10.8 and later.

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.

Historically, many classes decoded instances of themselves like this:

Swift

  • if let object = decoder.decodeObjectForKey("myKey") as MyClass {
  • ...succeeds...
  • } else {
  • ...fail...
  • }

Objective-C

  • id obj = [decoder decodeObjectForKey:@"myKey"];
  • if (![obj isKindOfClass:[MyClass class]]) {...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 initWithCoder: can conform to NSSecureCoding without any changes (assuming that it is a subclass of another class that conforms).

  • An object that does override initWithCoder: must decode any enclosed objects using the decodeObjectOfClass:forKey: method. For example:

    Swift

    • let obj = decoder.decodeObjectOfClass(MyClass.self, forKey: "myKey")

    Objective-C

    • id obj = [decoder decodeObjectOfClass:[MyClass class]
    • forKey:@"myKey"];

    In addition, the class must override its supportsSecureCoding method to return YEStrue.

For more information about how this relates to the NSXPC API, see Creating XPC Services in Daemons and Services Programming Guide.

  • Returns whether the class supports secure coding. (required)

    Declaration

    Swift

    static func supportsSecureCoding() -> Bool

    Objective-C

    + (BOOL)supportsSecureCoding

    Return Value

    Return YEStrue if your class supports secure coding, or NOfalse otherwise.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.8 and later.