Objective-c文件操作

开发中经常需要存储数据,应用程序产生的数据都会以文件形式进行存储。并且可读写

Plist

Plisy是Property List的简称,它是一种属性列表文件,专门用来存储序列化后的对象,并且以xml格式存储。

创建

1.在IDE中创建Plist文件:File-New File-OS X -Resource -property list-选择文件存储路径和文件名-完成

在其中添加两个字典类型的记录
2.在代码中创建:
        //指定存储路径和文件名
        NSString *filePath =@"/Users/Skyf/Desktop/MyOCProject/TestPlist/TestPlist/Pepole.plist";
        //存字典对象
        NSMutableDictionary *nmDictionary =[NSMutableDictionary dictionary];
        [nmDictionary setObject:@"tom" forKey:@"name"];
        [nmDictionary setObject:@"3" forKey:@"age"];
        [nmDictionary setObject:@"phone" forKey:@"10001"];
        [nmDictionary writeToFile:filePath atomically:YES];
<span style="white-space:pre">	</span>//存array
<pre name="code" class="objc">        //指定存储路径和文件名
        NSString *filePath =@"/Users/Skyf/Desktop/MyOCProject/TestPlist/TestPlist/Man.plist";
        //创建一个array
        NSMutableArray *nsMArray =[NSMutableArray arrayWithObjects:@"one",@"two",@"three",nil];
        //存入plist
        [nsMArray writeToFile:filePath atomically:YES ];


 
  

        //指定存储路径和文件名

        NSString *filePath =@"/Users/Skyf/Desktop/MyOCProject/TestPlist/TestPlist/Man.plist";

        //创建一个array

        NSMutableArray *nsMArray =[NSMutableArrayarrayWithObjects:@"one",@"two",@"three",nil];

        //存入plist

        [nsMArray writeToFile:filePathatomically:YES ];

读取

        //根据路径读取字典类型并打印
        NSMutableDictionary *mutableD =[NSMutableDictionary dictionaryWithContentsOfFile:@"/Users/Skyf/Desktop/MyOCProject/TestPlist/Student.plist"];
        
        NSLog(@"%@",mutableD);
        
        //根据路径读取array 并遍历打印所以值
        NSMutableArray *mArraty =[NSMutableArray arrayWithContentsOfFile:@"/Users/Skyf/Desktop/MyOCProject/TestPlist/TestPlist/Person.plist"];
        
        for (int i=0; i<mArraty.count; i++) {
            NSString *str =[mArraty objectAtIndex:i];
            NSLog(@"下标为%d的值为%@",i,str);
</pre><pre name="code" class="objc"><span style="white-space:pre">	
<span style="font-family: Arial, Helvetica, sans-serif;">//读取字符串类型使用读取方法: </span>
+(instancetype)stringWithContentsOfFile:(NSString*)path usedEnconding:


NSFileManager

提供了操作目录的方法,还提供了一些列操作文件的方法
常见的NSFileManager方法: 点击打开链接


猜你喜欢

转载自blog.csdn.net/qq_14902389/article/details/51987109