Saving and Loading Objects From Disk Memory

Saving and Loading List Items

Even though in the previous part we built the basic functionality of the demo app, we still must add two more important features so it works as expected. This means that we must make it capable of saving the shopping list permanently to the disk, and also load the list from the disk (if exists) when the application gets launched.

As the structure of our data is a mutable array, we can easily write and read to and from the disk, using the methods that the NSMutableArray class provides. Obviously, for doing both of the above, we are going to create two separate functions. So, let’s get started with the next one, which is responsible for saving the contents of the array to a file. The file is named shopping_list:

The first two lines consist of a standard piece of code that returns the path to the documents directory of the app. Once we know that, we form the path to the file, specifying the file name at the same time. Lastly, the key to the above function is the writeToFile(_:atomically:) method of the NSMutableArray class. This is the one that actually saves the array contents to the disk.

By having the above method implemented, we can go ahead and call it where it’s needed. If you think of what we did in the previous part, you can assume that we are going to call it in two places: When a new item is added to the list, and when an existing item is removed from the list.

At first, go to the textFieldShouldReturn(textField:) delegate method of the textfield. Just right before the return command, make a call to the above method:

Nice, each new item now will be saved to the disk too. Also, let’s pay a visit to the removeItemAtIndex(index:) function too, where we actually delete an item. As we just did, let’s make a call to the save function and let’s add it as the last command as well:

With all the above we can be sure that any changes that might take place in our data, they will become permanent too.

Now, we can proceed by implementing the exact opposite functionality, the data loading. At first, let’s see the definition of the respective function:

It’s important to highlight the fact that we must always check if a file exists before we load its contents. In iOS, we do that by using the NSFileManager class exactly as shown above. If the file doesn’t exists and the condition returns false, nothing will happen at all. On the other hand, if the file exists, we initialise the shoppingList array with the contents of the file, and then we reload the tableview so it displays the loaded data.

As a last step, we must call this function. As we want the data to be loaded right after the app has been launched, we’ll do that in the viewDidLoad method:

The two functionalities we added to the application in this part, will become really helpful later, when we’ll handle the notification actions without running the app on the foreground.


Saving and Loading Objects From Disk Memory