通过读写 .plist 文件,我们可以在 iPhone 里记录或调取数据,下面就是 CocoaChina 会员“pjk1129” 分享的读写 .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
[array
[array
NSArray*paths=NSSearchPathForDirectori
NSString*path=[paths
NSString *filename=[pathstringByAppendingPathCom
[arraywriteToFile:filename
[array release];
读操作
NSArray*paths=NSSearchPathForDirectori
NSString*path=[paths
NSString *filename=[pathstringByAppendingPathCom
NSMutableArray *array=[[NSMutableArray alloc]initWithContentsOfFile:filename];
txt1.text=[array objectAtIndex:0];
txt2.text=[[NSString alloc] initWithFormat:@”%d”,[[arrayobjectAtIndex:1]intValue]];
txt3.text=[[NSString alloc] initWithFormat:@”%d”,[[arrayobjectAtIndex:2]intValue]];
[array release];
- NSBundle *bundle = [NSBundle mainBundle];//取得mainBundle
- NSString *plistPath = [bundle pathForResource:@"文件名"ofType:@"plist"]; //取得文件路径
// 或可以写成
NSString *plistPath = [[NSBundle mainBundle]pathForResource:@"文件名" ofType:@"plist"];
//读取到一个NSDictionary
NSDictionary *dictionary = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
//读取到一个NSArray
NSArray *array = [[NSArray alloc]initWithContentsOfFile:plistPath];