Saving data with UIDocument in iOS

Reading and writing data in iOS is a crucial thing if your app depends on it. In my app Stepr (iTunes link). I’ve made the naive mistake to save all my data into a plist file with a (too) simple mechanism and made my users not very happy with this approach. Stepr is basically a pedometer which reads the data from the M7 coprocessor in the iPhone 5s, compares it to a goal set by the user and saves all steps of a day into a file (more on this in a separate post). The user can view all the recorded steps afterwards in a statistic and watch the overall progress.

So what was wrong with saving into a plist file? In general – nothing. If you when your data is loaded and ready to get saved you are (probably) fine. But for Stepr things are a bit more complicated. The app utilizes Background Fetch to update the data even when the app is not active. Stepr will be launched in the background and gets about 30 seconds to do its stuff till iOS will quit it and querying the CoreMotion framework is threaded too, so you don’t really know when updates are done. So in the worst case Stepr tried to load data, tried to update it and saved it at nearly the same time. Data got corrupted and the plist file was broken – not good!

The solution to this problem was to switch to UIDocument for file operations. But how to do it right? I asked this question myself and found a very very good tutorial from Kevin Hunter from Silver Bay Technologies on how to implement UIDocument for your file operations. And the best thing of all – the tutorial also covers unit tests and test driven development (TDD)! After working through it my document knows when loading data is done, when it has unsaved data and when the data is saved – the data management in Stepr is very robust now…awesome!

Because of this tutorial I was able to solve my problem for Stepr, learnt a lot about TDD and had also some knowledge on how to develop a mechanism to migrate from the old plist file to the new UIDocument powered file with unit tests and all the nice stuff.

I just can highly recommend to read this tutorial, it’s one of the best I’ve found so far! (Link)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.