NSCoding Tutorial in IOS with Swift 4 : How to Save Data

ns coding tutorial

Data save in IOS

There are many different ways to save data to disk in iOS.Which are property list serialisation ,Sqlite ,core Data and NSCoding with File manager.Core data is used for the heavy data requirements .For the light data NSCoding is the best way to store the data.in this tutorial we will cover how to implement the NSCoding with swift 4.

Implementation of NSCoding

NSCoding is a protocol that can implement on the data classes to support encoding and decoding your data into a data buffer which can then be persisted to disk.

First you create the custom class which is subclass of NSObject and the implement the NSCoding protocol .you must required two functions for implementation one is Required initialiser and second this Encode function .Screen Shot 2018-03-25 at 3.20.40 PM.png

Save and Load Data with NSKeyedArchiever and NSKeyedUnArchiever

After the Implementation of the Employee Custom class .We will need to save the data in disk.To save the data in disk with NSCoding we need a File path with File manager….

File Path

Screen Shot 2018-03-25 at 1.48.12 PM.png

Save helper Function

After the creation of the File path we need the save helper function to save the data in disk for this we use NSKeyedArchiever class which store the object…..

Screen Shot 2018-03-25 at 1.51.10 PM.pngScreen Shot 2018-03-25 at 3.20.59 PM

 

 Load Data helper function

in this we use the NSkeyedunarchiver class and use the unarchiveObject function which contain the file path and then we downcast it into Employee class

Screen Shot 2018-03-25 at 3.20.52 PM.png

After that compile and run the app , see results…..

Screen Shot 2018-03-25 at 2.10.48 PM.png

Source Code

https://github.com/MuhammadALI877/SaveDataWithNSCoding

Leave a Comment

Your email address will not be published.