資料持久化,實際上就是將資料存放到網路或者硬碟上,這裡是儲存到本地的硬碟上,應用程式的本地硬碟是沙箱,沙箱實際上就是一個檔案夾,它下面有4個檔案夾。分別是Documents,Library,APP包和tmp檔案夾,Documents裡面主要是儲存使用者長期使用的檔案,Library裡面又有Caches和Preferences檔案夾,Caches裡面存放的是臨時的檔案,緩衝。Preferences裡面存放的是喜好設定。tmp裡面也是臨時的檔案,不過和Caches還有區別,APP包裡面是編譯後的一些檔案,包不能修改。
先建立一個Person類,定義3個屬性
.h檔案
#import
<Foundation/Foundation.h>
@interface Person :
NSObject<NSCoding>
{
NSString *name;
int age;
NSString *phone;
}
@property(nonatomic,retain)NSString
*name, *phone;
@property(nonatomic,assign)int age;
-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge;//初始化方法
@end
.m檔案
#import
"Person.h"
@implementation Person
@synthesize name,age,phone;
-(id)initWithName:(NSString *)aName phone:(NSString *)aPhone age:(int)aAge
{
[super
init];
if (self) {
self.name = aName;
self.phone = aPhone;
self.age = aAge;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder //將屬性進行編碼
{
[aCoder
encodeObject:self.name
forKey:@"name"];
[aCoder
encodeObject:self.phone
forKey:@"phone"];
[aCoder
encodeInteger:self.age
forKey:@"age"];
}
- (id)initWithCoder:(NSCoder *)aDecoder //將屬性進行解碼
{
NSString *name1 = [aDecoder decodeObjectForKey:@"name"];
NSString *phone1 = [aDecoder decodeObjectForKey:@"phone"];
int age1 = [aDecoder decodeIntegerForKey:@"age"];
[self
initWithName:name1
phone:phone1 age:age1];
return self;
}
@end
主程式中進行歸檔與反歸檔
- (void)loadView
{
self.view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
self.view.backgroundColor = [UIColor whiteColor];
Person *p1 = [[Person alloc]initWithName:@"jim" phone:@"654789" age:3];
Person *p2 = [[Person alloc]initWithName:@"tom" phone:@"5464" age:4];
//檔案的歸檔
NSMutableData *data = [NSMutableData data ];
//建立一個歸檔類
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:p1 forKey:@"Person1"];
[archiver encodeObject:p2 forKey:@"Person2"];
[archiver finishEncoding];
[archiver release];
//將資料寫入檔案裡
[data writeToFile:[self filePath] atomically:YES];
//反歸檔,從檔案中取出資料
NSMutableData *data1 = [NSMutableData dataWithContentsOfFile:[self filePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data1];
Person *p3 = [unarchiver decodeObjectForKey:@"Person1"];
Person *p4 = [unarchiver decodeObjectForKey:@"Person2"];
NSLog(@"%@ %@ %d",p3.name,p3.phone,p3.age);
NSLog(@"%@ %@ %d",p4.name,p4.phone,p4.age);
}
-(NSString *)filePath
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES)objectAtIndex:0];
NSString *path = [docPath stringByAppendingPathComponent:@"texts"];
// NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/texts"]; //兩種方法都可以
return path;
}