40

iOS读写json文件

 5 years ago
source link: http://www.cocoachina.com/ios/20190121/26179.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一.获取沙盒路径

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK