美文网首页
02-plist文件

02-plist文件

作者: AlanGe | 来源:发表于2017-08-16 01:27 被阅读5次
    //  ViewController.m
    //  plist文件
    
    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        /*
         1.根节点只能是数组或者字典
         
         需求:创建一个数组,通过plist文件的形式,将数组保存到Documents文件夹array.plist文件
         
         .plist的不足:
             只能保存数组和字典
             只能保存Bollean、Data、Date、Number、String这些基本的数据类型
         */
        
    //    [self saveArray];
    //    [self readArray];
        
        [self saveDict];
        [self readDict];
        
    }
    
    // 保存数组
    -(void)saveArray
    {
        // 1.创建一个数组
        NSArray *array = @[@"1",@"2",@"3"];
        
        // 2.拼接文件路径
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSLog(@"%@",documentsPath);
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"array.plist"];
        
        // 3.写入文件
        BOOL success = [array writeToFile:filePath atomically:YES];
        
        NSLog(@"保存数组 success = %@",success?@"YES":@"NO");
        /*
         如果目标文件不存在,会自动创建.
         atomically:线程安全
         */
    }
    
    // 读取数组
    -(void)readArray
    {
        // 1.文件路径
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"array.plist"];
        
        // 2.读取
        NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
        
        NSLog(@"读取数组 = %@",array);
    }
    
    // 保存字典
    -(void)saveDict
    {
        // 1.创建一个数组
        NSDictionary *dict = @{@"a":@"1",@"b":@"2",@"c":@"3"};
        
        // 2.拼接文件路径
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSLog(@"%@",documentsPath);
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"dict.plist"];
        
        // 3.写入文件
        [dict writeToFile:filePath atomically:YES];
    }
    
    // 读取字典
    -(void)readDict
    {
        // 1.文件路径
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *filePath = [documentsPath stringByAppendingPathComponent:@"dict.plist"];
        
        // 2.读取
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
        
        NSLog(@"读取字典 = %@",dict);
    }
    
    @end
    

    相关文章

      网友评论

          本文标题:02-plist文件

          本文链接:https://www.haomeiwen.com/subject/lhubrxtx.html