binpress

Learn Objective-C, Building an App (Part 10): Basic Data Persistence

Persistence is the ability to save files and content to disk, so that you can read it out later and be able to save stuff. Most apps use persistence of some sort; even if your app doesn’t create files, you may still have settings and configurations you want to save. iOS provides a number of formats to save different types of data. These include user defaults, property lists (plist), archived objects, text files, XML, SQL databases, and Core Data. In this post, we’ll talk about the first four formats. XML will be covered in a separate extension, as it uses additional software beyond the standard SDK, and Core Data is complex enough to be the subject of its own post. With the power and flexibility that Core Data provides, there is little need for standard SQL databases, and so we will not cover it here; there are many good tutorials on SQL on the Internet. Let’s get started.

Building the App

Open Xcode, create a new Single View Application, and call it “Persistence”. Make sure to not use storyboards; that’s a topic for another post. Open up the XIB file, and layout an interface like the one shown below.

If you need help building the interface, check out this post, or get in touch through the comments or email.

All UI controls are at the default settings except for the segmented control at the top, which has a third section. Make the following connections:

  • Outlet: Segmented Control as segments
  • Outlet: Progress view as progressBar
  • Outlet: Switch as cSwitch
  • Outlet: Activity Indicator as spinner
  • Outlet: Text field as textField
  • Outlet: “Start spinning” button as spinningButton
  • Outlet: Three sliders as slider1, slider2, slider3
  • Outlet: Text view as textBox
  • Action: spinningButton as toggleSpinner:
  • Action: Segmented control, switch, text field, and sliders as controlValueChanged:
  • Actions and Outlets Connection
  • Actions and Outlets Connection

Also, make CCViewController.h the delegate of the text view. Again, if you need help, get in touch through the comments or email. You can also download the project at the end of this post.

Implementing the Code

We have three methods to implement—one to toggle the spinner, one to save the state and value of most of our controls, and the delegate for the text view, where we will save the text view’s contents. The first one is easy:

  1. - (IBAction)toggleSpinner:(id)sender {
  2.     if (self.spinner.isAnimating) {
  3.         [self.spinner stopAnimating];
  4.         ((UIButton *)sender).titleLabel.text = @"Start spinning";
  5.     }
  6.     else {
  7.         [self.spinner startAnimating];
  8.         ((UIButton *)sender).titleLabel.text = @"Stop spinning";
  9.     }
  10. }

Here, we simply check to see if the spinner is spinning (animating), and toggle it the other way. We also update the button label to reflect its new action.

User Defaults

The next method is where most of the persistence work play in. We’ll check the sender argument, and save its value to an appropriate store location.

  1. - (IBAction)controlValueChanged:(id)sender {
  2.     if (sender == self.segments)
  3.         // Something
  4.     else if (sender == self.cSwitch)
  5.         // Something
  6.     else if (sender == self.textField)
  7.         // Something
  8.     else if (sender == slider1)
  9.         // Something
  10.     else if (sender == slider2)
  11.         // Something
  12.     else if (sender == slider3)
  13.         // Something
  14.     else
  15.         return;
  16. }

In the first instance, we’re going to save the selected segment into NSUserDefaults. NSUserDefaults allows you to store basic configuration information in key-value pairs. Per Apple’s documentation:

> The defaults system allows an > application to customize its behavior > to match a user’s preferences. For > example, you can allow users to > determine what units of measurement > your application displays or how often > documents are automatically saved. > Applications record such preferences > by assigning values to a set of > parameters in a user’s defaults > database. The parameters are referred > to as defaults since they’re commonly > used to determine an application’s > default state at startup or the way it > acts by default.

The code looks like this:

  1. if (sender == self.segments) {
  2.         int selectedSegment = ((UISegmentedControl *)sender).selectedSegmentIndex;
  3.         [[NSUserDefaults standardUserDefaults] setInteger:selectedSegment forKey:@"SelectedSegmentIndex"];
  4.     }

NSUserDefaults provides support for scalar types, so you don’t have to box the integer into an NSNumber. Other NSUserDefault “setters” include:

> -setBool:forKey: > -setFloat:forKey: > -setInteger:forKey: > -setObject:forKey: > -setDouble:forKey: > -setURL:forKey:

To remove a value by key, use -removeObjectForKey:.

Plist

Plists have been a standard way to store text and settings since the early days of Cocoa. Plist data can be either in XML or binary format, and it is possible to convert between the two formats. Although there are arguably better alternatives, plists are still a standard way of saving data in iOS and is baked into a number of Foundation classes for easy access. In this case, we’ll create a key-value dictionary and save its contents to a plist. This is the basic way of saving configuration information to plist.

Before we begin, let’s look at an example plist. You can find a number of them ~/Library/Preferences.

Plist Preview

The plist appears to be in an XML format, but if you open the file in a text editor, you see the incomprehensible binary nature of the file.

Plist Binary

In our case, we’ll let NSDictionary handle the data transfer. NSDictionary has a -writeToFile:atomically: method, which writes a “property list representation of the contents of the dictionary to a given path.” You can re-create the dictionary from the file using the initWithContentsOfFile: method.

Only certain object types can be written to plists. These include instances of NSData, NSDate, NSNumber, NSString, NSArray, and NSDictionary. -writeToFile:atomically: will check of all objects in the dictionary are of these types; if not, the method will return NO and the file will not be written.

To support writing this data, we need to create a mutable dictionary. Call it controlState, and add it to our controller. Then, we need to amend toggleSpinner: to save the spinner’s state to the dictionary:

  1. - (IBAction)toggleSpinner:(id)sender {
  2.     if (self.spinner.isAnimating) {
  3.         [self.spinner stopAnimating];
  4.         ((UIButton *)sender).titleLabel.text = @"Start spinning";
  5.         [self.controlState setValue:[NSNumber numberWithBool:NO] forKey:@"SpinnerAnimatingState"];
  6.     }
  7.     else {
  8.         [self.spinner startAnimating];
  9.         ((UIButton *)sender).titleLabel.text = @"Stop spinning";
  10.         [self.controlState setValue:[NSNumber numberWithBool:YES] forKey:@"SpinnerAnimatingState"];
  11.     }
  12. }

We’re just interacting with basic NSDictionary APIs. We do something similar in the second and third cases of controlValueChanged:

  1. else if (sender == self.cSwitch)
  2.         [self.controlState setValue:[NSNumber numberWithBool:self.cSwitch.enabled] forKey:@"SwitchEnabledState"];
  3.     else if (sender == self.textField)
  4.         [self.controlState setValue:self.textField.text forKey:@"TextFieldContents"];

Finally, we’ll save the dictionary at the end of controlValueChanged:.

  1. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  2.     NSString *documentsDirectoryPath = [paths objectAtIndex:0];
  3.     NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"componentState.plist"];
  4.     [self.controlState writeToFile:filePath atomically:YES];

We get the documents directory, and create a file path by appending the filename to the directory string. We pass it into the NSDictionary method, and tell it to write to the file atomically (writing to a temp file then renaming it to prevent data damage during the writing process—you either have the old version or the new, but nothing corrupt, in-between).

Archiving Objects

Foundation provides a mechanism to save data objects as binary data through a process of encoding/decoding objects. The encoding operation supports scalar types and objects that support the NSCoding protocol. Most Foundation data types already support this protocol. If you want to encode your own data objects, you’ll want to implement NSCoding as well. NSCoding defines two methods, which in a data class might be implemented as follows (variables and properties are assumed to be declared already):

  1. - (void)encodeWithCoder:(NSCoder *)encoder {
  2.     [encoder encodeObject:obj1 forKey:@"obj1Key"];
  3.     [encoder encodeInt:anInt forKey:@"IntValueKey"];
  4.     [encoder encodeFloat:aFloat forKey:@"FloatValueKey"];
  5. }
  6.  
  7. - (id)initWithCoder:(NSCoder *)decoder {
  8.     if (!(self = [super init]))
  9.         return nil;
  10.     obj1 = [decoder decodeObjectForKey:@"obj1Key"];
  11.     anInt = [decoder decodeObjectForKey:@"IntValueKey"];
  12.     aFloat = [decoder decodeObjectForKey:@"FloatValueKey"];
  13. }

If your class’s superclass also adopts NSCoding, you should call [super encodeWithCoder:encoder] and [super initWithCoder:decoder] in the respective methods. In our case, however, we are not defining a custom data class. All our archiving will be handled in the controller. Create a new NSMutableDictionary called sliderValues and add it as a property to the controller class. Now we add the slider values to the array as they change:

  1. else if (sender == slider1)
  2.         [self.sliderValues setValue:[NSNumber numberWithFloat:slider1.value] forKey:@"Slider1Key"];
  3.     else if (sender == slider2)
  4.         [self.sliderValues setValue:[NSNumber numberWithFloat:slider2.value] forKey:@"Slider2Key"];
  5.     else if (sender == slider3)
  6.         [self.sliderValues setValue:[NSNumber numberWithFloat:slider3.value] forKey:@"Slider3Key"];

Here’s how we encode the object (at the end of controlValueChanged:):

  1. NSMutableData *data = [NSMutableData data];
  2.     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  3.     [archiver encodeObject:self.sliderValues forKey:@"SliderValues"];
  4.     [archiver finishEncoding];
  5.     NSString *dataPath = [documentsDirectoryPath stringByAppendingPathComponent:@"archivedObjects"];
  6.     [data writeToFile:dataPath atomically:YES];

The archiver object is created with an instance of NSMutableData, and when the archive process is finished the data object contains a binary representation of the original object. This data can then be saved out to a path.

Archiving objects is a really easy way to save relatively complex data objects to a file. However, the data is written in a binary format, and as such can only be used on OS X and iOS. Also note that a number of other classes, including NSArray, support writing to plist, and most Foundation data classes support data encoding.

Finally, we have to instantiate the dictionaries; otherwise we’ll be writing to a null pointer:

  1. - (void)viewDidLoad {
  2.     [super viewDidLoad];
  3.     // Do any additional setup after loading the view, typically from a nib.
  4.     self.controlState = [NSMutableDictionary dictionary];
  5.     self.sliderValues = [NSMutableDictionary dictionary];
  6. }

Text File

It is relatively easy to save an NSString to a text file. Text files are human readable and can be made into an efficient cross-platform data source. We’re going to save the contents of the text field to a string, To do that, we have to implement a UITextViewDelegate method. Here’s the code:

  1. - (void)textViewDidChange:(UITextView *)textView {
  2.     NSString *textViewContents = textView.text;
  3.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  4.     NSString *documentsDirectoryPath = [paths objectAtIndex:0];
  5.     NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"TextViewContents.txt"];
  6.     [textViewContents writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  7. }

The method of interest is writeToFile:atomically:encoding:error: on an instance of NSString. The first argument is a file path, the second is a boolean, the third is one of a few constants (most of the time you’ll use NSUTF8StringEncoding), and you can pass a pointer to an error if you want to know if anything went wrong.

Restoring Data

We’ll restore all the data to the controls in viewWillAppear:. The APIs are pretty straightforward.

  1. - (void)viewWillAppear:(BOOL)animated {
  2.     [super viewWillAppear:animated];
  3.  
  4.     // Load segmented control selection
  5.     int selectedSegmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"SelectedSegmentIndex"];
  6.     self.segments.selectedSegmentIndex = selectedSegmentIndex;
  7.  
  8.     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  9.     NSString *documentsDirectoryPath = [paths objectAtIndex:0];
  10.  
  11.     // Load data from plist
  12.     if ([[self.controlState allKeys] count] == 0) {
  13.         NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:@"componentState.plist"];
  14.         self.controlState = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
  15.  
  16.         if ([[self.controlState objectForKey:@"SpinnerAnimatingState"] boolValue])
  17.             [self.spinner startAnimating];
  18.         else
  19.             [self.spinner stopAnimating];
  20.  
  21.         self.cSwitch.enabled = [[self.controlState objectForKey:@"SwitchEnabledState"] boolValue];
  22.  
  23.         self.progressBar.progress = [[self.controlState objectForKey:@"ProgressBarProgress"] floatValue];
  24.  
  25.         self.textField.text = [self.controlState objectForKey:@"TextFieldContents"];
  26.     }
  27.  
  28.     // Decode objects
  29.     if ([[self.sliderValues allKeys] count] == 0) {
  30.         NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:[documentsDirectoryPath stringByAppendingPathComponent:@"archivedObjects"]];
  31.         NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  32.         self.sliderValues = [decoder decodeObjectForKey:@"SliderValues"];
  33.         self.slider1.value = [[self.sliderValues objectForKey:@"Slider1Key"] floatValue];
  34.         self.slider2.value = [[self.sliderValues objectForKey:@"Slider2Key"] floatValue];
  35.         self.slider3.value = [[self.sliderValues objectForKey:@"Slider3Key"] floatValue];
  36.     }
  37.  
  38.     // Read text file
  39.     NSString *textViewData = [NSString stringWithContentsOfFile:[documentsDirectoryPath stringByAppendingPathComponent:@"TextViewContents.txt"] encoding:NSUTF8StringEncoding error:nil];
  40.     self.textBox.text = textViewData;
  41. }

First, we read values out of NSUserDefaults to restore the selected segment. Next, we get the documents path, then load the plist array using an NSDictionary method. We then read the values in the dictionary through the key and set the proper values on our controls. We do the same thing with the sliders, except that we have NSKeyedUnarchiver decode the binary data into a dictionary. Finally, we read in a text file using an NSString method and set the text inside the UITextView to that string.

That’s all there is to basic data persistence. When you quit and relaunch the app, all the settings and control values will still be there.

Download the project here.

This post is part of the Learn Objective-C in 24 Days course.

Author: Feifan Zhou

Scroll to Top