Object-c歸檔使用

1 使用XML歸檔

MAC OS X使用XML文檔存儲默認參數、應用程序設置和配置信息。

NSString、NSDictionary、NSArray、NSData或NSNumber類型,可以通過writeToFile:atomically方法將數據寫到文件中。字典和數組可以使用XML格式寫數據。

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    @"letter A",@"A",@"letter B",@"B",@"letter C",@"C",nil];
if([dict writeToFile:@"dict" atomically:YES]==NO){
    NSLog(@"寫入失敗");
}

這裏將數據寫入到dict文件中,atomically的屬性YES,表示先將數據庫寫入到臨時備份文件,成功後,即把數據寫入到文件中。

讀取文件內容可以使用:

dictionaryWithContentsOfFile;
arrayWithContentsOfFile;
dataWithContentsOfFile;
StringWithContentsOfFile;

2 NSKeyedArchiver

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    @"letter A",@"A",@"letter B",@"B",@"letter C",@"C",nil];
[NSKeyedArchiver archiveRootObject:dict toFile:@"dict.archive"];
[NSKeyedUnarchiver unarchiveObjectWithFile:@"dict.archive"];
for(NSString *str in dict){
    NSLog(@"%@:%S",str,[dict objectForKey:str]);
}

3 編碼和解碼

在使用NSKeyedArchiver歸檔Student對象時(student對象時自定義的對象),Student對象需實現NSCoding協議,添加encodeWithCoder編碼方法和initWithCoder解碼方法。

//encode
-(void) encodeWithCoder:(NSCoder*) coder{
    [coder encodeObject:name forKey:@"stu_name"];
    [coder encodeObject:email forKey:@"stu_email"];
}
//decode
-(id) initWithCoder:(NSCoder*) coder{
    name = [coder decodeObjectforKey:@"stu_name"];
    email = [coder decodeObjectforKey:@"stu_email"];
}

基本類型的編碼和解碼:

encodeBool:forKey  decodeBool:forKey
encodeInt:forKey decodeInt:forKey
encodeInt32:forKey decodeInt32:forKey
encodeInt64:forKey decodeInt64:forKey
encodeFloat:forKey decodeFloat:forKey
encodeDouble:forKey decodeDouble:forKey


4 使用NSData創建自定義檔案

使用NSData可以自定義歸檔各種對象。前提是對象實現encodeObject:forKey和initWithObjcetforKey。

NSMutableData *data = [NSMutableData data];  //創建一個可變的數據空間
NSKeyedArchiver *arch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
 
[arch encodeObject:stu1 forKey:@"stu"];
[arch encodeObject:book forKey:@"book"];
[arch finishEncoding];
 
[data writeToFile:@"test" atomically:YES];

5 使用歸檔深度複製

可以先對一個對象歸檔,然後解碼後,使用另一個引用指向解碼後的對象實現歸檔。整個過程可以不用使用文件,直接發生在內存中。

NSData *data;
NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",nil];
NSMutableArray *arr2;
 
data = [NSKeyedArchiver archiveDataWithRootObject:arr1];
arr2 = [NSKeyedArchiver unarchiveObjectWithData:data];

 

發佈了37 篇原創文章 · 獲贊 6 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章