html5 ios文件读写,iOS读写json文件

一.获取沙盒路径

每个iOS应用都有自己专属的应用沙盒,应用沙盒就是文件系统中的目录。但是iOS系统会将每个应用的沙盒目录与文件系统的其他部分隔离,应用必须待在自己的沙盒里,并只能访问自己的沙盒。

沙盒目录

包含内容

Documents

存放应用运行时生成的并且需要保留的数据,iCloud同步时会同步该目录

Library/Caches

存放应用运行时生成的数据,iCloud同步时不会同步该目录

Library/Preferences/

存放所有的偏好设置

tmp/

存放应用运行时的临时数据

获取文件路径:

//两种获取应用沙盒路径的不同方法

NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

NSString *preferencesPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Preferences"];

NSString *tmpPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];

//NSSearchPathForDirectoriesInDomains()返回的是一个数组,这是因为对于Mac OS可能会有多个目录匹配某组指定的查询条件,但是在iOS上只有一个匹配的目录

NSString *documentPath1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;

NSString *cachePath1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

NSString *tmpPath1 = NSTemporaryDirectory();

读写json文件

处理json数据主要是用了NSJSONSerialization这个类,这个类主要有下列三个API:

//判断传入的对象是否可以转化为json数据,如果可以,返回YES,否则返回NO。

+ (BOOL)isValidJSONObject:(id)obj;

//传入一个json数据,返回一个foundation对象

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError * _Nullable *)error;

//传入foundation对象,转化为json数据

+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError * _Nullable *)error;

实例:

NSArray *array = @[@1, @2, @3];

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:array,@"1",@"dongdong", @"name", nil];

//首先判断能否转化为一个json数据,如果能,接下来先把foundation对象转化为NSData类型,然后写入文件

if ([NSJSONSerialization isValidJSONObject:dic]) {

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:1 error:nil];

[jsonData writeToFile:jsonPath atomically:YES];

}

//在读取的时候首先去文件中读取为NSData类对象,然后通过NSJSONSerialization类将其转化为foundation对象

NSData *jsonData = [[NSFileManager defaultManager] contentsAtPath:jsonPath];

NSArray *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:1 error:nil];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值