在ios上读写plist格式文件的代码如下:
读:
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
//网上流行的下面两行注释掉的方法不好使,对ios,直接用bundle就行
//NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//NSString *path=[paths objectAtIndex:0];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *filename=[path stringByAppendingPathComponent:@”abc.plist”];
success = [fileManager fileExistsAtPath:filename];
if(success) {
NSMutableArray *array=[[NSMutableArray alloc] initWithContentsOfFile:filename];
expressLabel1.text=[array objectAtIndex:0];
expressLabel2.text=[[NSString alloc] initWithFormat:@”%d”,[[array objectAtIndex:1]intValue]];
expressLabel3.text=[[NSString alloc] initWithFormat:@”%d”,[[array objectAtIndex:2]intValue]];
[array release];
}
写:
NSString *name=[expressLabel1 text];
NSNumber *phoneNumber=[[NSNumber alloc] initWithInt:[[expressLabel2 text] intValue]];
NSNumber *age=[[NSNumber alloc] initWithInt:[[expressLabel3 text] intValue]];
NSMutableArray *array=[[NSMutableArray alloc]init];
[array addObject:name];
[array addObject:phoneNumber];
[array addObject:age];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
//同样,注释掉的这三行真机调试时不好使
//NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//NSString *path=[paths objectAtIndex:0];
//NSString *filename=[path stringByAppendingPathComponent:@”personal.plist”];
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *filename=[path stringByAppendingPathComponent:@”abc.plist”];
success = [fileManager fileExistsAtPath:filename];
[array writeToFile:filename atomically:YES];
[phoneNumber release];
[age release];
[array release];
在simulator调试时不会真的写abc.plist,只是对编译文件夹下的plist文件操作,对add进项目的plist文件不会有任何修改。
在真机调试时会出各种问题,这时你要删除iphone上的程序、shift+ctrl+k清除目标文件、把项目文件夹下的build文件夹中的内容全删掉。之后再调试,相信在simulator上调试好的程序在device上大部分情况就好使了。