IOS development application example of data storage writeToFile
Recently, we have to import and export data on the project, so I studied the storage of data. It is actually very simple.
Step 1: Obtain the path to which the file is about to be saved:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);//Use the C function NSSearchPathForDirectoriesInDomains to obtain the full path of the directory in the sandbox. This function has three parameters: directory type, he domain mask, and boolean value. The Boolean value indicates whether it is necessary to pass the ~ extension path. And the first parameter is unchanged, that is, NSSearchPathDirectory. The last two parameters in iOS are also unchanged, namely: NSUserDomainMask and YES.
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
Another way is to use the NSHomeDirectory function to get the path to 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 on this file layer of sandbox or create directories. Instead, you should create a new writable directory based on this, such as Documents, Library or temp.
NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];//Add Documents to the sandbox path, the specific reasons have been analyzed before!
The difference between the two is that using NSSearchPathForDirectoriesInDomains is safer than adding Document behind NSHomeDirectory. Because the file directory may change on the system sent in the future.
Step 2: Generate the file under this path:
NSString *FileName=[documentPath stringByAppendingPathComponent:fileName];//fileName is the file name that saves the file
Step 3: Write data into the file:
[data writeToFile:FileName atomically:YES];//Write 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
The above is an application example of the data storage writeToFile developed by IOS. If you have any questions, please leave a message or go to the community of this site to communicate and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!