標籤:style code color c int com
1、相關知識點:
<1> 可以利用NSKeyedArchiver 進行歸檔和恢複的物件類型:NSString 、NSDictionary、NSArray、NSData、 NSNumber等
<2> 使用是必須遵循NSCoding協議對象,實現兩個方法:
encodeWithCoder:歸檔對象時,將會調用該方法。
initWithCoder:每次從檔案中恢複對象時,調用該方法。
2、簡單例子闡述詳細步驟
<1> 建立一個學生對像HUStudent,遵循 NSCoding 協議,並給學生對像規定三個屬性:
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) double height;
@property (nonatomic, assign) int age;
<2> 利用第一個方法進行資料的儲存:需要說明需要儲存的屬性
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeDouble:self.height forKey:@"height"];
}
<3> 利用第二個方法解析對象:讀取對象屬性
- (id)initWithCoder:(NSCoder *)decoder
{
if(self = [super init])
{
self.name = [decoder decoderObjectForKey:@"name"];
self.age = [decoder decoderObjctForKey:@"age"];
self.height = [decoder decoderObjectForKey:@"height"];
}
return self;
}
<4> 在控制器中對模型對象進行賦值與讀取
>>模型對象的屬性賦值
//----1.新的模型對象
HUStudent * student = [[HUStudent alloc]init];
student.name = @"hulin";
student.age = 24;
student.height = 1.83;
// -----2.歸檔模型對象
NSString * doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject]; // 獲得Documents全路徑
NSString * path = [doc stringByAppendingPathComponent:@"student.plist"]; // 擷取檔案的全路徑
NSArray * array = @[student];
[NSKeyedArchiver archiveRootObject:array toFile:path]; // 將對象歸檔
//----- 3.讀模數型對象的屬性
NSString * doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject]; // 獲得 Documents全路徑
NSString * path = [doc stringByAppendingPathComponent:@"student.plist"]; // 獲得檔案的全路進
HUStudent * student = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; // 從檔案中讀取對象
NSLog(@"%@,%d,%f",student.name,student.age,student.height);
3、使用NSKeyedArchiver儲存資料注意事項:
如果程式中建立的子類和父類都遵循了NSCoding協議,要在encodeWithCoder:方法中加上[self encodeWithCode:encode](確保繼承的執行個體變數也能被 編碼);同樣在 initWithCoder:加上 self = [super initWithCoder:decoder](確保執行個體變數也能被解碼);