最简单的plist文件读写代码

来源:互联网 发布:node sass windows 编辑:程序博客网 时间:2024/06/06 17:12
在网上找了很多的plist读写代码,看起来都是满头雾水的,索性摸索了一下, 自己写了出来,还算简单,供大家参考。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

    //首先读取plist中的数据
    NSString*plistPath = [[NSBundlemainBundle] pathForResource:@"Setup"ofType:@"plist"];    //把Setup.plist文件放到项目中就ok了,文件名随意。
    NSDictionary*dictionary = [[NSDictionaryalloc] initWithContentsOfFile:plistPath]; //根据plistPath内容,将Setup.plist内容读入到一个NSMutableDictionary中 //如果仅仅是读取plist内容并显示的话,此处用NSDictionary即可。
     
    //将服务器信息填入视图
    serverIP    = [[dictionary objectForKey:@"ServerSetup"] objectForKey:@"Server"];  //读取"ServerSetup"层 的"Server"关键字下的内容
    serverPort  = [[dictionary objectForKey:@"ServerSetup"] objectForKey:@"Port"];
     
   //显示读取的内容。
    UIAlertView* alert =[[UIAlertView alloc] initWithTitle:@"IP地址"message:serverIP delegate:Nil cancelButtonTitle:@"OKey"otherButtonTitles:nil,nil];
    [alert show];
     
//将读取到的内容 放入变量中
    AccelemeterX = (int)[[dictionary objectForKey:@"Accelerometer"] objectForKey:@"X"];  
    AccelemeterY = (int)[[dictionary objectForKey:@"Accelerometer"] objectForKey:@"Y"];  
    AccelemeterZ = (int)[[dictionary objectForKey:@"Accelerometer"] objectForKey:@"Z"];  
    NSLog(@"x=%@,y=%@,z=%@",AccelemeterX,AccelemeterY,AccelemeterZ);
  
 
    //如下进行写plist操作,注意写plist操作,必须使用NSMutableDictionary才行
 NSString*plistPath = [[NSBundlemainBundle] pathForResource:@"Setup"ofType:@"plist"];            //把Setup.plist文件放到项目中就ok了,文件名随意。
 NSMutableDictionary*dictionary = [[NSMutableDictionaryalloc] initWithContentsOfFile:plistPath];   //根据plistPath内容,此处必须使用NSMutableDictionary
    [[dictionary objectForKey:@"ServerSetup"] setValue:@"abc.abc.abc.abc"forKey:@"Server"];          //将plist文件中“ServerSetup”下的“Server”关键字的内容改为“abc.abc.abc.abc”  
    [dictionary writeToFile:plistPath atomically:YES];    //要想将修改内容写入文件,必须执行这步,否则即使修改了也是没有落实到磁盘上的



描述:Setup.plist
图片:屏幕快照 2012-05-22 下午9.21.50.png 
描述:Setup.plist文件内容
图片:屏幕快照 2012-05-22 下午9.21.40.png 

原创粉丝点击