標籤:
建立一個工程,為ViewController。
建立兩個類為NJperson
NJperson.h
#import <Foundation/Foundation.h>
// 如果想將一個自訂對象儲存到檔案中必須實現NSCoding協議
@interface NJPerson : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double height;
@end
NJperson.m
#import "NJPerson.h"
@implementation NJPerson
// 當將一個自訂對象儲存到檔案的時候就會調用該方法
// 在該方法中說明如何儲存自訂對象的屬性
// 也就說在該方法中說清楚儲存自訂對象的哪些屬性
- (void)encodeWithCoder:(NSCoder *)encoder
{
NSLog(@"NJPerson encodeWithCoder");
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInteger:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"heigth"];
}
// 當從檔案中讀取一個對象的時候就會調用該方法
// 在該方法中說明如何讀取儲存在檔案中的對象
// 也就是說在該方法中說清楚怎麼讀取檔案中的對象
- (id)initWithCoder:(NSCoder *)decoder
{
NSLog(@"NJPerson initWithCoder");
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntegerForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"heigth"];
}
return self;
}
_______在項目中建立兩個按鈕:一個為save,一個為read。
- (void)saveBtnClick:(id)sender{
NJStudent *stu = [[NJStudent alloc] init];
stu.name = @"lnj";
stu.age = 28;
stu.height = 1.8;
// 2.擷取檔案路徑
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
NSLog(@"path = %@", path);
// 3.將自訂對象儲存到檔案中
[NSKeyedArchiver archiveRootObject:stu toFile:path];
}
- (void)readBtnClick:(id)sender {
// 1.擷取檔案路徑
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
// 2.從檔案中讀取對象
// NJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
iOS中歸檔的建立,資料寫入與讀取