Persistent Data

Most common Persistent data mechanism:

There are 4 type of persistent data in iOS

-Property lists

-Object archives (or archiving)

-SQLite3 (iOSís embedded relational database)

-Core Data (Apple provided persistence tool)


===remind

Similar to Windows MacOS and IOS has some private folders for application Document,temporary,... you can find those folders path using NSSearchPathForDirectoriesInDomains,example:

 

let paths = NSSearchPathForDirectoriesInDomains(

NSSearchPathDirectory.LibraryDirectory,

NSSearchPathDomainMask.UserDomainMask, true)

let libraryDirectory = paths[0] as String


for Temp folder another useful api is NSTemporaryDirectory() ex:


let tempPath = NSTemporaryDirectory()

let tempFile = tempPath.stringByAppendingPathComponent("tempFile.txt")


the same way that Android OS , IOS keeps files and documents belonging to an app in a private location which is only accessible by the app, 

=====

Property lists supports the following type of data , if your data model consists of only these types you can use Property lists to save data:


Array or NSArray

NSMutableArray

Dictionary or NSDictionary

NSMutableDictionary

NSData

NSMutableData

String or NSString

NSMutableString

NSNumber

NSDate


Property lists are generally used for settings & preferences


ex:

let myArray = [1, 2, 3]

let array = myArray as NSArray (casting for Swift!)

array.writeToFile("/folder/subfolder/myarray.txt", atomically:true)



Save and loading data model using Core data and ManagedObjectContext:

ManagedObjectContext  are the objects scheme recognized by system to manipulate persistent data used in low level layer in Core services , to make use of theme your job consist of 1)get a ManagedObjectContext from your app 2)insert/embed your data model into it.Then you are able to save/Load your data through ManagedObjectContext



We can retrieve ManagedObjectContext within your application by delegation

In fact by choosing "Use Core Data" when creating the project all required stub code for using this delegation will be automatically added to the APPDelegate class as below:


lazy var managedObjectContext: NSManagedObjectContext? = {

    // Returns the managed object context for the application (which is already bound to the persistent store

    // coordinator for the application.) This property is optional since there are legitimate error

    // conditions that could cause the creation of the context to fail.

    let coordinator = self.persistentStoreCoordinator

    if coordinator == nil {

        return nil

    }

    var managedObjectContext = NSManagedObjectContext()

    managedObjectContext.persistentStoreCoordinator = coordinator

    return managedObjectContext

}()


and later we can retrieve this ManagedObjectContext by casting with following code:

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext


There a simple code in ViewController showing this:


//Data model

import Foundation

import CoreData


class Contact: NSManagedObject {


    @NSManaged var name: String

    @NSManaged var age: NSNumber


}


//ViewController

import UIKit

import CoreData

class ViewController: UIViewController {


    @IBOutlet weak var tfName: UITextField!

    @IBOutlet weak var tfAge: UITextField!

    let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        

    }


    @IBAction func onSave(sender: AnyObject) {

        

       let entityDescription=NSEntityDescription.entityForName("Contact", inManagedObjectContext: managedObjectContext!)

        

        let contact=Contact(entity:entityDescription!,insertIntoManagedObjectContext:managedObjectContext)

        contact.name=tfName.text

        contact.age=NSNumber(integer: tfAge.text.toInt()!)

        var error:NSError?

        managedObjectContext?.save(&error)

        

        

      

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    @IBAction func onLoad(sender: AnyObject) {

        

        let entityDescription = NSEntityDescription.entityForName("Contact",inManagedObjectContext: managedObjectContext!)

        let request = NSFetchRequest()

        

        request.entity = entityDescription

        var error:NSError?

        var objects = managedObjectContext?.executeFetchRequest(request, error: &error)

        let results = objects

       

        

            let match = results?[0] as! NSManagedObject

            tfName.text = match.valueForKey("name") as! String

            var nsAge:NSNumber = match.valueForKey("age") as! NSNumber

            tfAge.text=nsAge.stringValue

        

        

    }


} 

 



 © Xosrov 2016