is it possible to save NSMutableArray or NSDictionary data as file in iOS?

前端 未结 2 1474
野趣味
野趣味 2020-12-01 01:06

I want to save an NSMutableArray or NSDictionary as a permanent file. Then, I would like to reopen the file later.

Is this possible? If so,

相关标签:
2条回答
  • 2020-12-01 01:24

    May be you can convert a Dictionary to JSON data.and write it to a file.

    NSDictionary *dict = /* the NSDictionary/NSArray you need to write */
    
    NSError *writeError = nil;
    NSData* data;
    data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&writeError];
    
    if (!writeError) {
        [data writeToFile:filePath atomically:YES];
    }
    
    0 讨论(0)
  • To write in file

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
    
    [myArray writeToFile:filePath atomically:YES];
    

    To read from file

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];
    
    myArray = [NSArray arrayWithContentsOfFile:filePath];
    

    myArray will be nil if file is not present. And NSDictionary has similar methods. Please check the reference for the details of these methods.

    0 讨论(0)
提交回复
热议问题