上一篇把 student 物件攤平後存進了 plist,但存進去的並不是一個 student 物件,而是一堆欄位陣列。要使用資料時,得反向操作把它還原成物件陣列。
BOOL isDirectory;
if ([fileManager fileExistsAtPath:studentFilePath isDirectory:&isDirectory] && !isDirectory) {
NSLog(@"存在 student.plist !!");
// 由 plist 直接產生陣列物件
NSArray *studentList = [NSArray arrayWithContentsOfFile:studentFilePath];
// 依寫入時的順序取出各欄位
NSArray *studentName = [studentList objectAtIndex:0];
NSArray *studentID = [studentList objectAtIndex:1];
NSArray *studentSex = [studentList objectAtIndex:2];
NSArray *studentImagePath = [studentList objectAtIndex:3];
// 遍歷各欄位,逐一還原成 student 物件
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(@"stuents:%s", [[studentArray description] UTF8String]);
}
2013-10-28 15:31:35.034 StudentPlist[2050:70b] stuents:(
"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"
)
arrayWithContentsOfFile: 讀取方便,但缺點是「欄位順序」成了隱性契約:寫入時是 name、id、sex、imagePath 的順序,讀取時就必須完全照著這個順序取。一旦有人調整了寫入端,讀取端不會編譯錯誤,只會安靜地拿到錯誤資料。
更穩健的替代方案是改用 NSDictionary 存放,以欄位名稱為 key:
// 寫入 NSArray *dictArray = [studentArray valueForKey:@"dictionaryRepresentation"]; // 概念示意 // 讀取時以 key 取值,順序不再重要
若資料量與結構日後會成長,建議直接考慮 NSCoding(encodeWithCoder:/initWithCoder:)或 Core Data,讓模型自己負責序列化,比手動攤平可靠得多。