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];

转载于:https://www.cnblogs.com/louisQian/p/5685112.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值