上一篇用 writeToFile:atomically: 存檔,格式由系統自行決定。若想明確指定編碼格式(XML 或二進位),就要透過 NSPropertyListSerialization,流程變成兩階段:
NSData。NSData 寫入檔案或 URL。反序列化時反向操作:先把檔案讀成 NSData,再解碼回原始的屬性列表物件。
if ([fileManager fileExistsAtPath:studentFilePath isDirectory:&isDirectory] && !isDirectory) {
NSLog(@"存在 student.plist !!");
} else {
NSLog(@"不存在 student.plist");
NSArray *studentArray = [self createStudentArray];
// 用 KVC 把物件攤平成 plist 支援的結構
NSArray *studentIDArray = [studentArray valueForKey:@"studentID"];
NSArray *studentNameArray = [studentArray valueForKey:@"studentName"];
NSArray *studentSexArray = [studentArray valueForKey:@"studentSex"];
NSArray *studentImagePathArray = [studentArray valueForKey:@"studentImagePath"];
NSArray *studentList = @[studentNameArray, studentIDArray, studentSexArray, studentImagePathArray];
NSError *error = nil;
// 依指定編碼格式轉為 NSData
// NSPropertyListXMLFormat_v1_0 為 XML;NSPropertyListBinaryFormat_v1_0 為二進位
NSData *studentInfoData = [NSPropertyListSerialization
dataWithPropertyList:studentList
format:NSPropertyListBinaryFormat_v1_0
options:0
error:&error];
if (studentInfoData) {
NSLog(@"studentInfoData:\n%s\n", [[studentInfoData description] UTF8String]);
if ([studentInfoData writeToFile:studentFilePath atomically:YES]) {
NSLog(@"將 student 陣列保存為屬性列表檔案成功!");
} else {
NSLog(@"將 student 陣列保存為屬性列表檔案不成功");
}
} else {
NSLog(@"轉換為 NSData 失敗:\n%s\n", [[error description] UTF8String]);
}
}
if ([fileManager fileExistsAtPath:studentFilePath isDirectory:&isDirectory] && !isDirectory) {
NSLog(@"存在 student.plist !!");
NSData *studentListData = [NSData dataWithContentsOfFile:studentFilePath];
if (studentListData) {
NSError *error = nil;
// 解碼回原始屬性列表物件
NSArray *studentList = [NSPropertyListSerialization
propertyListWithData:studentListData
options:0
format:NULL
error:&error];
if (studentList) {
NSArray *studentName = [studentList objectAtIndex:0];
NSArray *studentID = [studentList objectAtIndex:1];
NSArray *studentSex = [studentList objectAtIndex:2];
NSArray *studentImagePath = [studentList objectAtIndex:3];
NSMutableArray *studentArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [studentName count]; i++) {
Students *student = [[Students alloc]
initWithName:[studentName objectAtIndex:i]
ID:[[studentID objectAtIndex:i] intValue]
Sex:[studentSex objectAtIndex:i]
Photo:[studentImagePath objectAtIndex:i]];
[studentArray addObject:student];
}
NSLog(@"students:\n%s\n", [[studentArray description] UTF8String]);
} else {
NSLog(@"解碼為原始屬性列表物件失敗:%s", [[error description] UTF8String]);
}
}
}
2013-10-28 16:48:24.240 StudentPlist[2387:70b] students: (
"name:seal,id:110401,sex:girl,imagepath:seal.png",
"name:willing,id:110402,sex:boy,imagepath:willing.png",
"name:lisa,id:110403,sex:girl,imagepath:lisa.png"
)
讀取端的 format: 可以傳 NULL,讓系統自行判斷格式,這也是為什麼換格式時讀取端往往不需要改動。另外提醒,options: 參數在這裡指的是解碼時的相容性選項(例如遇到舊格式或未知資料的處理方式),與寫入時的格式選擇是不同概念。