In Swift you can convert an object into data, and all you have to do is
First, you need to have the object implement the NSObject and nscoding protocols.
Second, implement the following two methods:
Encodewithcoder
Init (coder Adecoder:nscoder)//an initializer with nscoder parameters
Example code:
classSerializableobject:nsobject, nscoding {var name:string?func Encodewithcoder (acoder:nscoder) {acoder.encodeobject (name!, Forkey:"name") } Overrideinit () {Self.name="My Object"} required init (coder Adecoder:nscoder) {Self.name= Adecoder.decodeobjectforkey ("name") as?String}}
If an object implements the Nscoding protocol, it can be converted to a NSData object.
Nskeyedarchiver-Serialization
Nskeyedunarchiver-Deserialization
Example code:
Let AnObject =serializableobject () anobject.name="My Thing that I ' m saving"//converting it to dataLet Objectconvertedtodata =Nskeyedarchiver.archiveddatawithrootobject (anobject)//converting it back//Note that the conversion might fail, so ' unarchiveobjectwithdata ' returns//An optional value. So, use the ' as? ' to check for see if it worked.Let Loadedobject =Nskeyedunarchiver.unarchiveobjectwithdata (objectconvertedtodata) as?Serializableobjectprint (Loadedobject?. Name//"My Thing that I ' m saving"
Swift Language Essentials-serialization and deserialization