Knowledge points for iOS file modules

Source: Internet
Author: User

1. The following key objects are in the file directory:

(1) Nsarray *nssearchpathfordirectoriesindomains (nssearchpathdirectory directory, Nssearchpathdomainmask DomainMask , BOOL Expandtilde)

(2) NSDocumentDirectory

(3) Nsuserdomainmask

(4) Nshomedirectory

2.

The iphone generates a private directory for each application, located in:

/users/sundfsun2009/library/application Support/iphone Simulator/user/applications,

A string of alphanumeric characters is generated as a directory name, and the alphanumeric string is different from the last time each time the application starts.

Therefore, the documents directory is usually used for persisting data persistence, and this documents directory can be obtained by:

Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes) got.

The code is as follows:

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);

NSString *documentsdirectory = [Paths objectatindex:0];

NSLog (@ "Path:%@", path);

The printing results are as follows:

Path:/users/apple/library/application support/iphone simulator/4.3/applications/ 550af26d-174b-42e6-881b-b7499faa32b7/documents

and through Nshomedirectory () can also get the directory of the program, the code is as follows:

NSString *destpath = Nshomedirectory ();

NSLog (@ "Path:%@", destpath);

The printing results are as follows:

Path:/users/apple/library/application support/iphone simulator/4.3/applications/ 550af26d-174b-42e6-881b-b7499faa32b7

Looking at the results of both prints, we can see the difference between the two methods

3. The main thing is to return an absolute path for storing the files we need to store.

(NSString *) DataFilePath {Nsarray*paths =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString*documentsdirectory = [Paths Objectatindex:0]; return[Documentsdirectory stringbyappendingpathcomponent:@"shoppingcar.plist"]; } Nsfilemanager* fm=[Nsfilemanager Defaultmanager]; if(![FM fileexistsatpath:[self DataFilePath]]) {  //The following is a save on the path to the file development[FM createdirectoryatpath:[self DataFilePath] Withintermediatedirectories:yes attributes:nil Error:nil]; //get all the filenames in a directoryNsarray *files =[FM subpathsatpath: [self datafilepath]]; //read a fileNSData *data =[FM contentsatpath:[self DataFilePath]; //orNSData *data =[NSData datawithcontentofpath:[self DataFilePath]; }  

4.

Because the application is in the sandbox (sandbox), the file read and write permissions are restricted, only a few directories to read and write files:

    • Documents: User data in the app can be placed here, itunes Backup and restore will include this directory
    • TMP: Store temporary files, itunes does not back up and restore this directory, files in this directory may be deleted after the app exits
    • Library/caches: Store cached files, itunes does not back up this directory, files in this directory will not be deleted in the app exit

Create a file in the documents directory

The code is as follows:

Nsarray *paths=nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmas   K, YES); NSLog (@"Get Document path:%@", [Paths Objectatindex:0]); NSString*filename=[[paths Objectatindex:0] stringByAppendingPathComponent:@"MyFile"]; NSString*content=@"a"; NSData*contentdata=[content datausingencoding:nsasciistringencoding]; if([Contentdata writetofile:filename Atomically:yes]) {NSLog (@">>write OK."); }  

You can login to the device via SSH to see the file generated in the documents directory.

The above is to create an ASCII encoded text file, if you want to take Chinese characters, such as:

NSString *filename=[[paths Objectatindex:0] stringbyappendingpathcomponent:@ "myFile " ];    *content=@ " Genzhen people have interest ";    *contentdata=[content datausingencoding:nsunicodestringencoding];    if ([Contentdata writetofile:filename Atomically:yes]) {      NSLog (@ ">>write OK. ) " );   }  

Create a file in another directory

If you want to specify a different file directory, such as the caches directory, you need to replace the Catalog factory constants, the above code is the same:

Nsarray *paths=nssearchpathfordirectoriesindomains (nscachesdirectory                                                  , Nsuserdomainmask                                                   , YES);  

Use Nssearchpathfordirectoriesindomains to locate only the caches directory and the documents directory.

TMP directory, can not follow the above method to obtain the directory, there is a function to obtain the application's root directory:

Nshomedirectory ()

This is the parent directory of documents, and of course the parent directory of the TMP directory. Then the file path can be written like this:

NSString *filename=[nshomedirectory () stringbyappendingpathcomponent:@ "Tmp/myfile.txt"];

Or, more directly, you can use this function:

Nstemporarydirectory ()

However, the resulting path would be:

.../tmp/-tmp-/myfile.txt

Working with resource files

Resource files are often used when writing application projects, such as:

After installing to the device, it is in the app directory:

The following code shows how to get to a file and print the contents of the file:

[OBJC]View Plaincopy
  1. NSString *myfilepath = [[NSBundle Mainbundle]
  2. Pathforresource:@ "F"
  3. OfType:@ "TXT"];
  4. NSString *myfilecontent=[nsstring stringwithcontentsoffile:myfilepath encoding:nsutf8StringEncoding   error: nil];
  5. NSLog (@ "Bundel file path:%@ \nfile content:%@", myfilepath,myfilecontent);

Code Run Effect:

Knowledge points for iOS file modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.