ios application data storage: writeToFile

Recently, the project needs to import and export data, so I studied the preservation of data, which is actually very simple.

 

Step 1: Get the path where the file will be saved:

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);//Use the C function NSSearchPathForDirectoriesInDomains to get the full path of the directory in the sandbox. The function has three parameters, the directory type, the domain mask, and a boolean value. The boolean value indicates whether the path needs to be extended through ~. And the first parameter is unchanged, namely NSSearchPathDirectory. The last two parameters are also unchanged in iOS , namely: NSUserDomainMask and YES.
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];

Another way is to use the NSHomeDirectory function to get the path of the sandbox. The specific usage is:
NSString *sandboxPath = NSHomeDirectory();
// Once you have the full sandbox path, you can create a path from it, but you cannot write files or create a directory on this file layer of the sandbox, but should be Create a new writable directory on this basis, such as Documents, Library or temp.
NSString *documentPath = [sandboxPath
            stringByAppendingPathComponent:@"Documents"];//Add Documents to the sandbox path, the specific reasons were analyzed earlier!

The difference between the two is that it is safer to use NSSearchPathForDirectoriesInDomains than to add Document after NSHomeDirectory. Because the file directory may change on future sending systems.

 

 

Step 2: Generate files in this path:

NSString *FileName=[documentPath stringByAppendingPathComponent:fileName];//fileName is the file name of the saved file

 

Step 3: Write data to the file:

[data writeToFile:FileName atomically:YES];//Write the NSData type object data to the file, the file name is FileName

 

 

Finally: read the data from the file:

NSData *data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//Read data from FileName

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326134978&siteId=291194637