对模型对象进行归档

FourLines.h

 1 #import <Foundation/Foundation.h>
 2 #import <UIKit/UIKit.h>
 3 
 4 
 5 @interface FourLines : NSObject <NSCoding,NSCopying>{
 6     NSString *field1;
 7     NSString *field2;
 8     NSString *field3;
 9     NSString *field4; 
10 }
11 
12 @property (nonatomic,retain)NSString *field1;
13 @property (nonatomic,retain)NSString *field2;
14 @property (nonatomic,retain)NSString *field3;
15 @property (nonatomic,retain)NSString *field4;
16 
17 @end

FourLines.m

#import "FourLines.h"

#define kField1Key    @"Field1"
#define kField2Key    @"Field2"
#define kField3Key    @"Field3"
#define kField4Key    @"Field4"

@implementation FourLines

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

/**
 将对象编码到文档中
 */
#pragma mark NSCoding
-(void)  encodeWithCoder:(NSCoder *)enCoder{
    
    [enCoder encodeObject:field1 forKey:kField1Key];
    [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] retain];
        field2 = [[decoder decodeObjectForKey:kField2Key] retain];
        field3 = [[decoder decodeObjectForKey:kField3Key] retain];
        field4 = [[decoder decodeObjectForKey:kField4Key] retain];
    }
    return self;
}

#pragma mark -
#pragma mark NSCopying
-(void)copyWithZone:(NSZone *)zone{
    FourLines *copy = [[[self class] allocWithZone:zone] init ];
    copy.field1 = [[self.field1 copyWithZone:zone] autorelease];
    copy.field2 = [[self.field2 copyWithZone:zone] autorelease];
    copy.field3 = [[self.field3 copyWithZone:zone] autorelease];
    copy.field4 = [[self.field4 copyWithZone:zone] autorelease];
    
    return copy;
}
@end

PersistenceViewController.h

 1 #import <UIKit/UIKit.h>
 2 
 3 #define kFileName    @"data.list"
 4 #define kFileName    @"archive"
 5 #define kDataKey    @"Data"
 6 
 7 @interface PersistenceViewController : UIViewController {
 8     UITextField *field1;
 9     UITextField *field2;
10     UITextField *field3;
11     UITextField *field4;
12 }
13 @property (nonatomic,retain)IBOutlet UITextField *field1;
14 @property (nonatomic,retain)IBOutlet UITextField *field2;
15 @property (nonatomic,retain)IBOutlet UITextField *field3;
16 @property (nonatomic,retain)IBOutlet UITextField *field4;
17 
18 - (NSString *)dataFilePath;
19 -(void)applicationWillResignActive:(NSNotification *)notification;
20 
21 @end

PersistenceViewController.m

  1 #import "PersistenceViewController.h"
  2 #import "FourLines.h"
  3 
  4 @implementation PersistenceViewController
  5 @synthesize field1;
  6 @synthesize field2;
  7 @synthesize field3;
  8 @synthesize field4;
  9 
 10 //用于返回数据文件的完整路径名,它通过查找Document目录并对对其附加kFilename累执行该操作。
 11 -(NSString *)dataFilePath{
 12     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 13     NSString *documentsDirectory = [paths objectAtIndex:0];
 14     return [documentsDirectory stringByAppendingFormat:kFileName];
 15 }
 16 
 17 #pragma mark -
 18 
 19 /*
 20 // The designated initializer. Override to perform setup that is required before the view is loaded.
 21 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 22     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 23     if (self) {
 24         // Custom initialization
 25     }
 26     return self;
 27 }
 28 */
 29 
 30 /*
 31 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 32 - (void)loadView {
 33 }
 34 */
 35 
 36 
 37 
 38 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 39 //在该方法中,我们做了一下操作
 40 /**
 41     1,检查数据文件是否存在
 42     2,数据文件存在,使用该引用订阅UIApplicationWillReSignActiveNotification.
 43     3,我们使用NSNotificationCenter的默认实例,以及addObserver:select:name:object方法。我们传递一个observer即self、这就意味着
 44  PersistenceViewController是需要通知的对象。
 45  */
 46 - (void)viewDidLoad {
 47     NSString *filePath = [self dataFilePath];
 48     if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
 49         NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
 50         field1.text = [array objectAtIndex:0];
 51         field2.text = [array objectAtIndex:1];
 52         field3.text = [array objectAtIndex:2];
 53         field4.text = [array objectAtIndex:3];
 54         
 55         [array release];
 56         
 57         NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
 58         
 59         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
 60         
 61         FourLines *fourLine = [unarchiver decodeObjectForKey:kDataKey];
 62         
 63         [unarchiver finishDecoding];
 64         
 65         field1.text = fourLine.field1;
 66         field2.text = fourLine.field2;
 67         field3.text = fourLine.field3;
 68         field4.text = fourLine.field4;
 69         
 70         [unarchiver release];
 71         [data release];
 72         
 73     }
 74     
 75     UIApplication *app = [UIApplication sharedApplication];
 76     [[NSNotificationCenter defaultCenter] addObserver:self
 77                                              selector:@selector(applicationWillResignActive:)
 78                                             name:UIApplicationWillResignActiveNotification
 79                                                object:app];
 80     [super viewDidLoad];
 81 }
 82 
 83 /**
 84     
 85  */
 86 -(void)applicationWillResignActive:(NSNotification *)notification{
 87     NSMutableArray *array = [[NSMutableArray alloc] init ];
 88     [array addObject:field1.text];
 89     [array addObject:field2.text];
 90     [array addObject:field3.text];
 91     [array addObject:field4.text];
 92     
 93     [array writeToFile: [self dataFilePath] atomically:YES];
 94     [array release];
 95     
 96     FourLines *fourLine = [[FourLines alloc] init];
 97     fourLine.field1 = field1.text;
 98     fourLine.field2 = field2.text;
 99     fourLine.field3 = field3.text;
100     fourLine.field4 = field4.text;
101     
102     NSMutableData *data = [[NSMutableData alloc] init];
103     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
104     [archiver encodeObject:fourLine
105                     forKey:kDataKey];
106     [archiver finishEncoding];
107     [data writeToFile:[self dataFilePath] atomically:YES];
108     [fourLine release];
109     [archiver release];
110     [data release];
111     
112 }
113 
114 
115 
116 /*
117 // Override to allow orientations other than the default portrait orientation.
118 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
119     // Return YES for supported orientations
120     return (interfaceOrientation == UIInterfaceOrientationPortrait);
121 }
122 */
123 
124 - (void)didReceiveMemoryWarning {
125     // Releases the view if it doesn't have a superview.
126     [super didReceiveMemoryWarning];
127     
128     // Release any cached data, images, etc that aren't in use.
129 }
130 
131 - (void)viewDidUnload {
132     // Release any retained subviews of the main view.
133     // e.g. self.myOutlet = nil;
134     self.field1 = nil;
135     self.field2 = nil;
136     self.field3 = nil;
137     self.field4 = nil;
138     [super viewDidUnload];
139 }
140 
141 
142 - (void)dealloc {
143     [field1 release];
144     [field2 release];
145     [field3 release];
146     [field4 release];
147     [super dealloc];
148 }
149 
150 @end

posted on 2012-05-02 15:12  生于凛冽,葬于北邙  阅读(238)  评论(0编辑  收藏  举报

导航