Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning iOS5 Development.pdf
Скачиваний:
7
Добавлен:
09.05.2015
Размер:
15.6 Mб
Скачать

CHAPTER 13: Basic Data Persistence

449

Multiple-File Persistence

Using multiple files for persistence is an alternative approach. For example, an e-mail application might store each e-mail message in its own file.

There are obvious advantages to this method. It allows the application to load only data that the user has requested (another form of lazy loading), and when the user makes a change, only the files that changed need to be saved. This method also gives you the opportunity to free up memory when you receive a low-memory notification. Any memory that is being used to store data that the user is not currently viewing can be flushed, and then simply reloaded from the file system the next time it’s needed.

The downside of multiple-file persistence is that it adds a fair amount of complexity to your application. For now, we’ll stick with single-file persistence.

Next, we’ll get into the specifics of each of our persistence methods: property lists, object archives, SQLite3, and Core Data. We’ll explore each of these in turn and build an application that uses each mechanism to save some data to the device’s file system. We’ll start with property lists.

Using Property Lists

Several of our sample applications have made use of property lists, most recently when we used a property list to specify our application preferences. Property lists are convenient. They can be edited manually using Xcode or the Property List Editor application. Also, both NSDictionary and NSArray instances can be written to and created from property lists, as long as the dictionary or array contains only specific serializable objects.

Property List Serialization

A serialized object is one that has been converted into a stream of bytes so it can be stored in a file or transferred over a network. Although any object can be made serializable, only certain objects can be placed into a collection class, such as an NSDictionary or NSArray, and then stored to a property list using the collection class’s writeToFile:atomically: method. The following Objective-C classes can be serialized this way:

NSArray

NSMutableArray

NSDictionary

NSMutableDictionary

NSData

NSMutableData

www.it-ebooks.info

450CHAPTER 13: Basic Data Persistence

NSString

NSMutableString

NSNumber

NSDate

If you can build your data model from just these objects, you can use property lists to save and load your data.

If you’re going to use property lists to persist your application data, you’ll use either an NSArray or an NSDictionary to hold the data that needs to be persisted. Assuming that all of the objects that you put into the NSArray or NSDictionary are serializable objects from the preceding list, you can write a property list by calling the writeToFile:atomically: method on the dictionary or array instance, like so:

[myArray writeToFile:@"/some/file/location/output.plist" atomically:YES];

NOTE: In case you were wondering, the atomically parameter tells the method to write the data to an auxiliary file, not to the specified location. Once it has successfully written the file, it will then copy that auxiliary file to the location specified by the first parameter. This is a safer

way to write a file, because if the application crashes during the save, the existing file (if there was one) will not be corrupted. It adds a bit of overhead, but in most situations, it’s worth the

cost.

One problem with the property list approach is that custom objects cannot be serialized into property lists. You also can’t use other delivered classes from Cocoa Touch that aren’t specified in the previous list of serializable objects, which means that classes like NSURL, UIImage, and UIColor cannot be used directly.

Apart from the serialization issue, keeping all your model data in the form of property lists means that you can’t easily create derived or calculated properties (such as a property that is the sum of two other properties), and some of your code that really should be contained in model classes must be moved to your controller classes. Again, these restrictions are OK for simple data models and simple applications. Most of the time, however, your application will be much easier to maintain if you create dedicated model classes.

Simple property lists can still be useful in complex applications. They are a great way to include static data in your application. For example, when your application has a picker, often the best way to include the list of items for it is to create a plist file and place that file in your project’s Resources folder, which will cause it to be compiled into your application.

Let’s a build a simple application that uses property lists to store its data.

www.it-ebooks.info

CHAPTER 13: Basic Data Persistence

451

The First Version of the Persistence Application

We’re going to build a program that lets you enter data into four text fields, saves those fields to a plist file when the application quits, and then reloads the data back from that plist file the next time the application launches (see Figure 13–2).

Figure 13–2. The Persistence application

NOTE: In this chapter’s applications, we won’t be taking the time to set up all the user interface niceties that we have added in previous examples. Tapping the return key, for example, will neither dismiss the keyboard nor take you to the next field. If you want to add such polish to the

application, doing so would be good practice, so we encourage you to do that on your own.

Creating the Persistence Project

In Xcode, create a new project using the Single View Application template, name it Persistence, and make sure to turn off the Use Storyboard option. This project contains all the files that we’ll need to build our application, so we can dive right in.

www.it-ebooks.info

452

CHAPTER 13: Basic Data Persistence

Before we build the view with the four text fields, let’s create the outlets we need. Expand the Classes folder. Then single-click the BIDViewController.h file, and make the following changes:

#import <UIKit/UIKit.h>

@interface BIDViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *field1; @property (weak, nonatomic) IBOutlet UITextField *field2; @property (weak, nonatomic) IBOutlet UITextField *field3; @property (weak, nonatomic) IBOutlet UITextField *field4;

-(NSString *)dataFilePath;

-(void)applicationWillResignActive:(NSNotification *)notification;

@end

In addition to defining four text field outlets, we’ve also defined two additional methods. One method, dataFilePath, will create and return the full pathname to our data file by concatenating a file name onto the path for the Documents directory. The other method, applicationWillResignActive: will be called when our application quits and will save data to the plist file. We’ll discuss these methods when we edit the persistence classes.

Next, select BIDViewController.xib to edit the GUI.

Designing the Persistence Application View

Once Xcode switches over to Interface Builder mode, click the View icon to open the View window in the nib editing pane. Drag a Text Field from the library, and place it against the top and right blue guidelines. Bring up the attributes inspector. Make sure the box labeled Clear When Editing Begins is unchecked.

Now, drag a Label to the window, and place it to the left of the text field using the left blue guideline, and use the horizontal centering blue guideline to line up the label with the text field. Double-click the label and change it to say Line 1:. Finally, resize the text field using the left resize handle to bring it close to the label. Use Figure 13–3 as a guide.

Next, select the label and text field, hold down the option key, and drag down to make a copy below the first set. Use the blue guidelines to guide your placement. Now, select both labels and both text fields, hold down the option key, and drag down again. You should have four labels next to four text fields. Double-click each of the remaining labels and change their names to Line 2:, Line 3:, and Line 4:. Again, compare your results with Figure 13–3.

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]