First, we will summarize how to obtain the documents directory. In iOS development, we often need to retrieve the complete path of the documents directory for reading and writing files. I have summarized the following two methods:
1. nsstring * documentsdirectory = [nshomedirectory () stringbyappendingpathcomponent: @ "documents"];
2. nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes );
Nsstring * documentsdirectory = [paths objectatindex: 0];
The documentsdirectory above is the complete path of the obtained documents.
ProgramAll resource files are stored in the package. The method to obtain the package path is as follows:
Nsstring * appdirectory = [[nsbundle mainbundle] bundlepath];
In actual development, we sometimes need to determine whether a resource file under documents exists. If it does not exist, we will copy it from the package. Now we assume that the file to be determined is "xxx.txt ".CodeAs follows:
Nsfilemanager * filemanager = [nsfilemanager defaultmanager];
Nsstring * filepath = [self [documentsdirectory stringbyappendingpathcomponent: @ "xxx.txt"];
If (! [Filemanager fileexistsatpath: filepath]) // if it does not exist
{
Nslog (@ "xxx.txt is not exist ");
Nsstring * datapath = [[[nsbundle mainbundle] bundlepath] stringbyappendingstring: @ "/xxx.txt"]; // obtain the path of the corresponding file in the package
Nserror * error;
If ([filemanager copyitematpath: datapath topath: filepath error: & error]) // copy
{
Nslog (@ "Copy xxx.txt success ");
}
Else
{
Nslog (@ "% @", error );
}
}