Monday, May 30, 2016

Store data in plist with NSFileManager

This example is written in Swift 2.2 with Xcode 7.3.1.

For an iOS app, permanent data may be stored in CoreData, in a simple text file, or in a plist file. This example stores information in a plist file. The steps

1. Add a new property list file:

2. Edit the key, type and value of the plist as below:

3. Modify ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    var num   : Int = 0
    var label : UILabel!
    let path = NSHomeDirectory()+"/Documents/Storage.plist"
    var dictionary : NSMutableDictionary!
    let fileManager = NSFileManager.defaultManager()
    override func viewDidLoad() {
        dictionary = NSMutableDictionary(contentsOfFile: path)
        let button = UIButton(frame: CGRectMake(0,0,100,30)) =
        button.setTitle("Generate", forState: UIControlState.Normal)
        button.addTarget(self, action: #selector(btnGenerate), forControlEvents: UIControlEvents.TouchUpInside)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        label = UILabel(frame: CGRectMake(0,0,100,30)) = CGPointMake(,
        label.textAlignment = NSTextAlignment.Center
        label.text = "\(num)"
        let buttonDel = UIButton(frame: CGRectMake(0,0,100,30)) = CGPointMake(,
        buttonDel.setTitle("Delete plist", forState: UIControlState.Normal)
        buttonDel.addTarget(self, action: #selector(btnDel), forControlEvents: UIControlEvents.TouchUpInside)
        buttonDel.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        buttonDel.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
    func btnGenerate() {
        num = Int(arc4random()%100)
        label.text = "\(num)"
        dictionary = NSMutableDictionary(contentsOfFile: path)
    func btnDel() {
        label.text = "0"
        do {
            try fileManager.removeItemAtPath(path)
        } catch {
            print("Unable to delete the plist file")
    func checkFile() {
        if !fileManager.fileExistsAtPath(path) {
            print("File not exist!")
            let srcPath = NSBundle.mainBundle().pathForResource("Storage", ofType: "plist")
            do {
                //Copy the project plist file to the documents directory.
                try fileManager.copyItemAtPath(srcPath!, toPath: path)
            } catch {
                print("File copy error!")
    func read() {
        label.text = "\(dictionary!.objectForKey("Num")!)"
    func write() {
        dictionary.setValue(num, forKey: "Num")
        dictionary.writeToFile(path, atomically: true)

    override func didReceiveMemoryWarning() {

Related Information:

NSSearchPathForDirectoriesInDomains - Read/Write a file in an iOS app

No comments:

Post a Comment