iOS Serialisation and Encoding
NSCoding and NSSecureCoding
iOS comes with two protocols for object serialisation for Objective-C or NSObject
s: NSCoding
and NSSecureCoding
. When a class conforms to either of the protocols, the data is serialized to NSData
: a wrapper for byte buffers. Note that Data
in Swift is the same as NSData
or its mutable counterpart: NSMutableData
. The NSCoding
protocol declares the two methods that must be implemented in order to encode/decode its instance-variables. A class using NSCoding
needs to implement NSObject
or be annotated as an @objc class. The NSCoding
protocol requires to implement encode and init as shown below.
when init(coder:)
is part of the class. Next, when decoding the object, a check should be made, e.g.:
The conformance to NSSecureCoding
ensures that objects being instantiated are indeed the ones that were expected. However, there are no additional integrity checks done over the data and the data is not encrypted. Therefore, any secret data needs additional encryption and data of which the integrity must be protected, should get an additional HMAC.
Object Archiving with NSKeyedArchiver
NSKeyedArchiver
is a concrete subclass of NSCoder
and provides a way to encode objects and store them in a file. The NSKeyedUnarchiver
decodes the data and recreates the original data. Let's take the example of the NSCoding
section and now archive and unarchive them:
You can also save the info in primary plist NSUserDefaults
:
Codable
It is a combination of the Decodable
and Encodable
protocols. A String
, Int
, Double
, Date
, Data
and URL
are Codable
by nature: meaning they can easily be encoded and decoded without any additional work. Let's take the following example:
You can also use codable to save the data in the primary property list NSUserDefaults
:
JSON Encoding
XML
When not using third party libraries, but Apple's XMLParser
, be sure to let shouldResolveExternalEntities
return false
.
References
Last updated
Was this helpful?