zoukankan      html  css  js  c++  java
  • ios本地文件内容读取,.json .plist 文件读写

    ios本地文件内容读取,.json .plist 文件读写

    本地文件.json .plist文件是较为常用的存储本地数据的文件,对这些文件的操作也是一种常用的基础。

    本文同时提供初始化变量的比较标准的写法,如果你有更好的初始化变量的写法,欢迎留言提醒我。

    .json文件的数据获取需要通过赋值NSData,再通过NSJSONSerialization 方法将NSData数据转成NSArray 或NSDictionary进行使用。

    .plist文件的数据可以直接进行访问。

    //获取本地location.json文件内容

    @property (nonatomic, strong) NSArray *locData;
    
    - (NSArray *)locData {
    
        if (!_locData) {
    
            NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"location" ofType:@"json"]];
    
            NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
    
            NSMutableArray *newArray = [NSMutableArray array];
    
            for (NSDictionary *dict in dataArray) {
    
                XCFLocation *loc = [XCFLocation locationWithDict:dict];
    
                [newArray addObject:loc];
    
            }
    
            _locData = newArray;
    
        }
    
        return _locData;
    
    }
    
    //获取本地keywords.plist文件内容
    
    @property (nonatomic, strong) NSArray *hotSearchWords;
    
    - (NSArray *)hotSearchWords {
    
        if(!_hotSearchWords) {
    
            NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"keywords" ofType:@"plist"]];
    
            NSArray *array = [NSArray arrayWithArray:dataDict[@"content"][@"keywords"]];
    
            NSMutableArray *mArray = [NSMutableArray array];
    
            for (NSString *word in array) {
    
                [mArray addObject:word];
    
            }
    
            _hotSearchWords = mArray;
    
        }
    
        return _hotSearchWords;
    
    }
    
     
    
    //写入.plist文件
    
    NSString *filename = [[NSBundle mainBundle] pathForResource:@"keywords" ofType:@"plist”];
    
    NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"keywords" ofType:@"plist"]];
    
    [dataDict setObject:@"add some content" forKey:@"c_key"]; 
    
    [dataDict writeToFile:filename atomically:YES];
    
    
    追寻最真
  • 相关阅读:
    VS-Visual Studio-IIS Express 支持局域网访问
    JAVA和C# 3DES加密解密
    Js调用Java方法并互相传参
    Cannot find SS.INI file for user *** 解决方法
    $.ajax()方法参数详解
    HANA Studio打开系统显示Secure storage is locked
    C#通过ODBC查询HANA数据库数据
    IIS7发布asp.net mvc提示404.0
    CentOS 搭建git服务
    解决用navicat远程连接数据库出现1045 access denied for user 'root'@'localhost' using password yes
  • 原文地址:https://www.cnblogs.com/zhao-jie-li/p/5839884.html
Copyright © 2011-2022 走看看