Skip to content

Persistent storage: files

Prepared and tested with Xcode 9 and Swift 4

In this tutorial we cover the following topics


General information


Methods we can use

In this tutorial we will show persistent storage method based on files. We will examine three options, each offering different possibilities imposing other requirements.

  • Using UserDefaults Simply speaking, with UserDefaults any data that is reasonably simply structured can be stored with just a few lines of code. It's very easy to use and for small amount of data is more than enought. With UserDefaults we can save the following data types:
    • Bool,
    • Number types,
    • String,
    • Array,
    • Dictionary,
    • Date,
    • URL,
    • Data (a byte buffer in memory Data).
  • Using .write and .loadTextmethods from NSString class We can store and load text data using Foundation NSString's object method (NSString and String).
  • Using NSKeyedArchiver/NSKeyedUnarchiver with NSCoding protocol With this we can save custom objects. NSKeyedArchiver encodes (saves) while NSKeyedUnarchiver decodes (retrieves) any NSCoding compliant classes we want persisted. NSCoding is a protocol that requires two methods: required init(coder decoder: NSCoder) and encode(with coder: NSCoder). Any class that conforms to NSObject and NSCoder, can be serialized (translated from its current data structure into a format that can be stored as bytes sequence) and deserialized (extracted from bytes sequence into a data structure) into data that can be saved to a user’s disk.

You can read also meterial related to Objective-C and iOS: Basic data storage

In the following sections we will create a class which can be used to save our data using the described methods.


Apple file system remarks

  • User have not access to directories for which he does not have the appropriate security privileges.
  • Application is expected to follow certain conventions regarding the location of different files for different purposes.
  • There are commonly used directory defined by constants located in FileManager.SearchPathDirectory:
    • .applicationSupportDirectory,
    • .desktopDirectory,
    • .documentDirectory,
    • .libraryDirectory,
    • .moviesDirectory,
    • .musicDirectory,
    • .picturesDirectory.
  • Another set of constants is defined in FileManager.SearchPathDomainMask. Search path domain constants specifying base locations for the FileManager.SearchPathDirectory type. We have the following set of constants
    • .allDomainsMask,
    • .localDomainMask,
    • .networkDomainMask,
    • .systemDomainMask,
    • .userDomainMask.
  • Terms serialize, archive, and encode very often are used interchangably. The right meaning is as follow: The program archives an object, by instructing it to encode itself, which results a serialized data.


Persist with UserDefaults

  1. Step 1: setting up a project in Xcode
    Launch Xcode and select File | New | Project... from main menu or from Welcome to Xcode screen select Create a new Xcode project.
    In project window select macOS | Application | Cocoa App template and then click the Next button.

    You will see the project options sheet. Name it macOSPersistWithUserDefaults. Completed sheet should look like below

    Press Next button, and you will be prompted for a location for your project. When selected, press Create to save the project.
  2. Step 2: add a new class
    Select File | New | File... to create a new Swift class and name it PersistentTestUserDefaults

    Add the following PersistentTestUserDefaults class definition to the PersistentTestUserDefaults.swift file
  3. Step 3: add viewDidAppear method skeleton
    Add viewDidAppear method to ViewController.swift file
  4. Step 4: add testUserDefaults method
    Add testUserDefaults method to ViewController.swift file
  5. Step 5: modify saveDefaults method
  6. Add / modify saveDefaults method located in PersistentTestUserDefaults class
  7. Step 6: modify loadDefaults method
  8. Add / modify loadDefaults method located in PersistentTestUserDefaults class
  9. Step 7: make a test
    Run the application. You should see

    object forKey: valueBool, value: true
    object forKey: valueInt, value: 123
    object forKey: valueFloat, value: 4.56
    object forKey: valueDouble, value: 7.89
    object forKey: valueObject, value: Object
    object forKey: valueArray, value: [1, 2, 3]
    object forKey: valueDictionary, value: ["b": 2, "a": 1, "c": 3]
    object forKey: valueString, value: Just a string
    object forKey: valueDate, value: 2017-11-28 11:31:23 +0000
    object forKey: valueBool, value: true
    object forKey: valueInt, value: 123
    object forKey: valueFloat, value: 4.56
    object forKey: valueDouble, value: 7.89
    object forKey: valueObject, value: Object
    object forKey: valueArray, value: [1, 2, 3]
    object forKey: valueDictionary, value: ["b": 2, "a": 1, "c": 3]
    object forKey: valueString, value: Just a string
    object forKey: valueURL, value: http://fulmanski.pl/tutorials

    printed as an output.


Persist with NSString

  1. Step 1: setting up a project in Xcode
    Launch Xcode and select File | New | Project... from main menu or from Welcome to Xcode screen select Create a new Xcode project.
    In project window select macOS | Application | Cocoa App template and then click the Next button.

    You will see the project options sheet. Name it macOSPersistWithString. Completed sheet should look like below

    Press Next button, and you will be prompted for a location for your project. When selected, press Create to save the project.
  2. Step 2: add a new class
    Select File | New | File... to create a new Swift class and name it PersistentTestString

    Add the following PersistentTestString class definition to the PersistentTestUserDefaults.swift file
  3. Step 3: add viewDidAppear method skeleton
    Add viewDidAppear method to ViewController.swift file
  4. Step 4: add testString method
    Add testString method to ViewController.swift file
  5. Step 5: modify saveString method
  6. Add / modify saveString method located in PersistentTestUserDefaults class
  7. Step 6: modify loadString method
  8. Add / modify loadString method located in PersistentTestUserDefaults class
  9. Step 7: make a test
    Run the application. You should see

    Some text to save

    printed as an output.


Persist with NSKeyedArchiver/NSKeyedUnarchiver with NSCoding

  1. Step 1: setting up a project in Xcode
    Launch Xcode and select File | New | Project... from main menu or from Welcome to Xcode screen select Create a new Xcode project.
    In project window select macOS | Application | Cocoa App template and then click the Next button.

    You will see the project options sheet. Name it macOSPersistWithNSKeyedArchiver. Completed sheet should look like below

    Press Next button, and you will be prompted for a location for your project. When selected, press Create to save the project.
  2. Step 2: add a new class
    Select File | New | File... to create a new Swift class and name it PersistentTestNSKeyedArchiver

    Add the following PersistentTestPersistWithNSKeyedArchiver class definition to the PersistentTestNSKeyedArchiver.swift file
  3. Step 3: add viewDidAppear method skeleton
    Add viewDidAppear method to ViewController.swift file
  4. Step 4: add testArchive method
    Add testArchive method to ViewController.swift file
  5. Step 5: creating an NSCoding-compliant class
    Select File | New | File... to create a new Swift class and name it ArchiveObject

    Add the following ArchiveObject class definition to the ArchiveObject.swift file
  6. Step 6: modify saveArchive method
  7. Add / modify saveArchive method located in PersistentTestUserDefaults class
  8. Step 7: modify loadArchive method
  9. Add / modify loadArchive method located in PersistentTestUserDefaults class
  10. Step 8: make a test
    Run the application. You should see

    true 123 [4, 5, 6]

    printed as an output.
  11. Step 9: modify testArchive method
    Add / modify testArchive in ViewController.swift file
  12. Step 10: add saveArchiveWithUserDefaults method
  13. Add / modify saveArchiveWithUserDefaults method located in PersistentTestUserDefaults class
  14. Step 11: add loadArchiveWithUserDefaults method
  15. Add / modify loadArchiveWithUserDefaults method located in PersistentTestUserDefaults class
  16. Step 12: make a test
    Run the application. You should see

    false 654 [3, 2, 2]

    printed as an output.