`

新风作浪博客学习(一)plist文件读写操作

    博客分类:
  • ios
阅读更多
文件plist 全名Property List,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,因此通常被称为 plist文件。文件是xml格式的。file->new->file->左边选Resource 右边选 Property List点右下角的next然后起名,出来的就是你要的plist文件


         此处用例举一个plist文件的Demo,只是对plist文件简单的读写操作


        新建工程命名plistFile,class Prefix  填写PF,然后next

[img]

[/img]


开始的时候并没有加入plist文件,除了工程自动生成的plistFile-Info.plist,然后直接在PFViewContoller.m文件中的viewDidLoad添加代码:
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
//    读取plist文件
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"testInfo" ofType:@"plist"];
    
    NSMutableDictionary *data=[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; 
//    打印出plist文件
    NSLog(@"%@",data);   
//    写入plist文件
    [data setObject:@"test1" forKey:@"key1" ];
    [data setObject:@"test2" forKey:@"key2"];

    [data writeToFile:@"testInfo.plist" atomically:YES];
    
    NSLog(@"%@",data);   
    NSLog(@"%@",[data objectForKey:@"key2"]);
}




这样做的目的只是想测试一下如果我们没有手工创建一个plist文件,当我们读取的时候系统会不会自动创建一个plist文件,测试结果是系统不会生成plist文件,输出plist文件内容为nil,运行结果截图:
[img]

[/img]


然后我们在手动创建一个plist文件,命名为testInfo.plist
[img]

[/img]

[img]

[/img]

[img]

[/img]


通过手动创建了plist文件后再次运行,可以读取数据:
[img]

[/img]



但是当我们打开testInfo.plist文件时,发现没有内容,这个有些不理解:
[img]

[/img]




然后我们在testInfo.plist文件右键Add Row,就可在里面添加数据;
[img]

[/img]


手动在testInfo.plist中添加了如下数据,然后点击运行:
[img]

[/img]

[img]

[/img]


从结果中我们可以看出,Key1,和key2在第一个NSLog打印中没有,因为key1和key2是在第一个NSLog后在写入testInfo.plist之中;


怎样用代码在向testInfo.plist中添加一个数组呢,在ViewDidLoad后面添加如下代码,即可以实现:
NSArray *array = [[NSArray alloc] initWithObjects:@"tes11",@"test12",@"test13",@"test14", nil];//数组初始化
    [data setObject:array forKey:@"arraytest"];//设置数组键值
    [data writeToFile:@"customInfo.plist" atomically:YES];//将数组数据写入testInfo.plist文件中
     NSLog(@"%@",data);



运行结果截图如下:
[img]

[/img]


  • 大小: 180.8 KB
  • 大小: 12.9 KB
  • 大小: 95.2 KB
  • 大小: 169.3 KB
  • 大小: 140.6 KB
  • 大小: 18.5 KB
  • 大小: 114 KB
  • 大小: 130.6 KB
  • 大小: 125.1 KB
  • 大小: 29.6 KB
  • 大小: 40.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics