zoukankan      html  css  js  c++  java
  • 以plist文件做本地存储

    1、把需要保存的信息已plist文件形式保存在本地,即写入沙盒:

    /**
     *  写入本地(plist文件)
     */
    - (void)saveArray
    {
        // 1.获得沙盒根路径
        NSString *home = NSHomeDirectory();
        
        // 2.document路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        // 3.新建数据
        NSDictionary *dict = @{@"haha":@"11",
                               @"hehe":@"12",
                               @"huhu":@"13",
                               @"gogo":@"14"
                               };
        
        NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
        
        
        [dict writeToFile:filepath atomically:YES];
    }
    

      其中Decuments是沙盒固定路径,data.plist是自己取的要保存的文件的名字;

    2、当需要拿出保存的信息的时候,读取保存在本地的plist文件:

    /**
     *  读取写入本地的plist文件
     */
    - (IBAction)read {
        // 1.获得沙盒根路径
        NSString *home = NSHomeDirectory();
        
        // 2.document路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        // 3.文件路径
        NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
        
        // 4.读取数据
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filepath];
        
        NSLog(@"%@", dic);
    }
    

      

    3、有时保存在本地的文件信息不是最新时,需要删除上次保存在本地的文件,然后重新保存的最新的信息在本地:

    /**
     *  删除保存在本地的plist文件的数据
     */
    - (void)remove{
        // 1.获得沙盒根路径
        NSString *home = NSHomeDirectory();
        
        // 2.document路径
        NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
        
        // 3.文件路径
        NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        [fileManager removeItemAtPath:filepath error:nil];
    }
    

      这样就完成了文件的本地存储。

    对于小文件的存储,减少了用数据库存储的麻烦,以plist文件存储,轻便、快捷,操作简单。

    有时候对于网络数据的缓存,如果数据不是很打的话,也是可以用plist文件存储的。

  • 相关阅读:
    mysql 表的类型
    【Mysql优化】key和index区别
    [置顶] 步步辨析JS中的对象成员
    [置顶] C语言单元测试框架
    代码规范总结
    AFNetworking、MKNetworkKit和ASIHTTPRequest对比
    在SQL中使用PL/SQL函数存在的问题
    C++中一个函数隐藏的有趣例子
    深入浅出Mybatis-分页
    SRM 207 Div II Level Two: RegularSeason,字符串操作(sstream),多关键字排序(操作符重载)
  • 原文地址:https://www.cnblogs.com/h-tao/p/5226400.html
Copyright © 2011-2022 走看看