当前位置: 移动技术网 > 移动技术>移动开发>IOS > iOS开发中本地文件.json .plist 文件读写教程

iOS开发中本地文件.json .plist 文件读写教程

2018年02月08日  | 移动技术网移动技术  | 我要评论

iOS开发中本地文件.json .plist 文件读写教程,本地文件.json .plist文件是较为常用的存储本地数据的文件,对这些文件的操作也是一种常用的基础。

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

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

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

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

- (NSArray *)jsonData {

        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"xxxx" 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];

        }
    return newArray;
}

//获取本地xxxx.plist文件内容

- (NSArray *)plistArray {
        NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"xxxx" ofType:@"plist"]];

        NSArray *array = [NSArray arrayWithArray:dataDict[@"content"][@"keywords"]];

        NSMutableArray *mArray = [NSMutableArray array];

        for (NSString *word in array) {

            [mArray addObject:word];

        }
    return mArray;
}

//写入.plist文件

NSString *filename = [[NSBundle mainBundle] pathForResource:@"xxxx" ofType:@"plist”];

NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"xxxx" ofType:@"plist"]];

[dataDict setObject:@"add some content" forKey:@"c_key"]; 

[dataDict writeToFile:filename atomically:YES];

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网