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

460

CHAPTER 13: Basic Data Persistence

second nature, as all you’re really doing is storing and retrieving your object’s properties using key-value coding.

The Archiving Application

Let’s redo the Persistence application so it uses archiving instead of property lists. We’re going to be making some fairly significant changes to the Persistence source code, so you might want to make a copy of your project before continuing.

Implementing the BIDFourLines Class

Once you’re ready to proceed and have a copy of your Persistence project open in Xcode, select the Persistence folder and press N or select File New New File…. When the new file assistant comes up, select Cocoa Touch, select Objective-C class, and click Next. On the next screen, name the class BIDFourLines, and select NSObject in the Subclass of control. Click Next again. Then choose the Persistence folder to save the files, and click Create. This class is going to be our data model. It will hold the data that we’re currently storing in a dictionary in the property list application.

Single-click BIDFourLines.h, and make the following changes:

#import <Foundation/Foundation.h>

@interface BIDFourLines : NSObject

@interface BIDFourLines : NSObject <NSCoding, NSCopying>

@property (copy, nonatomic) NSString *field1; @property (copy, nonatomic) NSString *field2; @property (copy, nonatomic) NSString *field3; @property (copy, nonatomic) NSString *field4;

@end

This is a very straightforward data model class with four string properties. Notice that we’ve conformed the class to the NSCoding and NSCopying protocols. Now, switch over to BIDFourLines.m, and add the following code:

#import "BIDFourLines.h"

#define

kField1Key

@"Field1"

#define

kField2Key

@"Field2"

#define

kField3Key

@"Field3"

#define

kField4Key

@"Field4"

@implementation BIDFourLines

@synthesize field1; @synthesize field2; @synthesize field3; @synthesize field4;

#pragma mark NSCoding

- (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:field1 forKey:kField1Key];

www.it-ebooks.info

CHAPTER 13: Basic Data Persistence

461

[encoder encodeObject:field2 forKey:kField2Key]; [encoder encodeObject:field3 forKey:kField3Key]; [encoder encodeObject:field4 forKey:kField4Key];

}

- (id)initWithCoder:(NSCoder *)decoder { if (self = [super init]) {

field1 = [decoder decodeObjectForKey:kField1Key]; field2 = [decoder decodeObjectForKey:kField2Key]; field3 = [decoder decodeObjectForKey:kField3Key]; field4 = [decoder decodeObjectForKey:kField4Key];

}

return self;

}

#pragma mark -

#pragma mark NSCopying

- (id)copyWithZone:(NSZone *)zone {

BIDFourLines *copy = [[[self class] allocWithZone:zone] init]; copy.field1 = [self.field1 copyWithZone:zone];

copy.field2 = [self.field2 copyWithZone:zone]; copy.field3 = [self.field3 copyWithZone:zone]; copy.field4 = [self.field4 copyWithZone:zone]; return copy;

}

@end

We just implemented all the methods necessary to conform to NSCoding and NSCopying. We encode all four of our properties in encodeWithCoder: and decode all four of them using the same four key values in initWithCoder:. In copyWithZone:, we create a new BIDFourLines object and copy all four strings to it. See? It’s not hard at all.

Implementing the BIDViewController Class

Now that we have an archivable data object, let’s use it to persist our application data. Select BIDViewController.m, and make the following changes:

#import "BIDViewController.h"

#import "BIDFourLines.h"

#define kFilename

@"data.plist"

#define

kFilename

@"archive"

#define

kDataKey

@"Data"

@implementation BIDViewController @synthesize field1;

@synthesize field2; @synthesize field3; @synthesize field4;

- (NSString *)dataFilePath {

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

www.it-ebooks.info

462

CHAPTER 13: Basic Data Persistence

 

return [documentsDirectory stringByAppendingPathComponent:kFilename];

 

}

 

#pragma mark -

 

- (void)viewDidLoad {

 

[super viewDidLoad];

 

// Do any additional setup after loading the view, typically from a nib.

 

NSString *filePath = [self dataFilePath];

 

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {

 

NSArray *array =[[NSArray alloc] initWithContentsOfFile:filePath];

 

field1.text = [array objectAtIndex:0];

 

field2.text = [array objectAtIndex:1];

 

field3.text = [array objectAtIndex:2];

 

field4.text = [array objectAtIndex:3];

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

BIDFourLines *fourLines = [unarchiver decodeObjectForKey:kDataKey]; [unarchiver finishDecoding];

field1.text = fourLines.field1; field2.text = fourLines.field2; field3.text = fourLines.field3; field4.text = fourLines.field4;

}

UIApplication *app = [UIApplication sharedApplication]; [[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(applicationWillResignActive:)

name:UIApplicationWillResignActiveNotification

object:app];

}

.

.

.

- (void)applicationWillResignActive:(NSNotification *)notification { NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:field1.text]; [array addObject:field2.text]; [array addObject:field3.text]; [array addObject:field4.text];

[array writeToFile:[self dataFilePath] atomically:YES];

BIDFourLines *fourLines = [[BIDFourLines alloc] init]; fourLines.field1 = field1.text;

fourLines.field2 = field2.text; fourLines.field3 = field3.text; fourLines.field4 = field4.text;

NSMutableData *data = [[NSMutableData alloc] init]; NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]

initForWritingWithMutableData:data];

[archiver encodeObject:fourLines forKey:kDataKey]; [archiver finishEncoding];

www.it-ebooks.info

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