原文地址:http://hi.baidu.com/sushii/blog/item/51e0203e57964bfe55e723e9.html
想在一個類裡把個數組寫進.plist檔案裡,再在另一個類裡從這個.plist檔案把數組讀取出來?
以name,phoneNumber,age三個欄位,為例。我是做的iphone,在文字框中輸入資料,擷取後,裝入數組中。然後把數組寫入.plist檔案
寫操作
NSString *name=[txt1 text];
NSNumber *phoneNumber=[[NSNumber alloc] initWithInt:[[txt2 text] intValue]];
NSNumber *age=[[NSNumber alloc] initWithInt:[[txt3 text] intValue]];
NSMutableArray *array=[[NSMutableArray alloc]init];
[array addObject:name];
[array addObject:phoneNumber];
[array addObject:age];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
NSString *filename=[path stringByAppendingPathComponent:@"personal.plist"];
[array writeToFile:filename atomically:YES];
[array release];
讀操作
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *path=[paths objectAtIndex:0];
NSString *filename=[path stringByAppendingPathComponent:@"personal.plist"];
NSMutableArray *array=[[NSMutableArray alloc] initWithContentsOfFile:filename];
txt1.text=[array objectAtIndex:0];
txt2.text=[[NSString alloc] initWithFormat:@"%d",[[array objectAtIndex:1] intValue]];
txt3.text=[[NSString alloc] initWithFormat:@"%d",[[array objectAtIndex:2] intValue]];
[array release];