iOS Developer Library

Developer

Foundation Framework Reference NSCoding Protocol Reference

Options
Deployment Target:

On This Page
Language:

NSCoding

Inherits From


Not Applicable

Conforms To


Not Applicable

Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later

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).

In keeping with object-oriented design principles, an object being encoded or decoded is responsible for encoding and decoding its instance variables. A coder instructs the object to do so by invoking encodeWithCoder: or initWithCoder:. encodeWithCoder: instructs the object to encode its instance variables to the coder provided; an object can receive this method any number of times. initWithCoder: instructs the object to initialize itself from data in the coder provided; as such, it replaces any other initialization method and is sent only once per object. Any object class that should be codable must adopt the NSCoding protocol and implement its methods.

It is important to consider the possible types of archiving that a coder supports. On OS X version 10.2 and later, keyed archiving is preferred. You may, however, need to support classic archiving. For details, see Archives and Serializations Programming Guide.

  • Returns an object initialized from data in a given unarchiver. (required)

    Declaration

    Swift

    init(coder decoder: NSCoder)

    Objective-C

    - (id)initWithCoder:(NSCoder *)decoder

    Parameters

    decoder

    An unarchiver object.

    Return Value

    self, initialized using the data in decoder.

    Discussion

    You must return self from initWithCoder:. If you have an advanced need that requires substituting a different object after decoding, you can do so in awakeAfterUsingCoder:.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later

  • Encodes the receiver using a given archiver. (required)

    Declaration

    Swift

    func encodeWithCoder(_ encoder: NSCoder)

    Objective-C

    - (void)encodeWithCoder:(NSCoder *)encoder

    Parameters

    encoder

    An archiver object.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later