iOS Development-File operations

Source: Internet
Author: User

Directory Operations and file management

Learning Goals

1. Understanding a single case

2. Master the Nsfilemanager class commonly used in file management exercises

3. Master the Nsfilehandle class commonly used file data operation

4. Understand common operations of the NSData class

5. master plist file reading and writing

——————————————————————

Usually the program in the run or after the end of the program need to save some information, and need to persist storage information, such as login information, video playback records, collection records and so on, then we can use the following methods to persist the data.

1.1 Singleton Mode (current object has and only one instance)

Benefit: Only one instance, data sharing.

Singleton mode is a common design pattern. When you apply this mode,

The class of a singleton object must guarantee that only one instance exists, and it instantiates itself and to the entire

This instance is provided by the system. If you want an object of a class in the system to exist only one,

A singleton mode is the best solution.

In fact, a single case is similar to a global variable in C language

During the entire program declaration cycle, only one copy of the object exists in memory

You can share data between multiple objects.

<1> Single-instance creation

(1) The singleton creation method usually starts with Default/shared/standard and so on.

(2) The singleton does not require release or autorelease, because the life cycle of the singleton is the entire program.

2. Method:

2.1 Nsfilemanager

<1>Create a File Manager singleton object [Nsfilemanager Defaultmanager]<2>traversing the contents of a directory//shallow traversal of files in the current directory/*Contentsofdirectoryatpath: Path to traverse error: Error message*/Nsarray*array = [[Nsfilemanager Defaultmanager] Contentsofdirectoryatpath:path error:&ERROR]; //Deep TraversalArray=[Filemanger Subpathsofdirectoryatpath:path error:nil];<3>determine if a file exists/*Be sure to add a suffix when judging if the file exists.         If there is a suffix in path for the file, no suffix indicates the folder. */BOOL isexist=[Filemanger Fileexistsatpath:path]; if(isexist) {NSLog (@"exist"); }        Else{NSLog (@"does not exist"); } <4>creating files and directories//Create a file  /*Createfileatpath: Path to create file contents: File contents (nsdata type) attributes: File attributes, typically Nil,nil, with default properties. */        //Note: If the file already exists, it will overwriteBOOL Createok=[Filemanger createfileatpath:path contents:nil Attributes:nil]; //Create a directory/*Createdirectoryatpath: The directory to be created, if the folder already exists does not overwrite withintermediatedirectories: There is an intermediate directory attributes: Folder The attribute, nil represents the default property error: Error message*/Createok= [Filemanger createdirectoryatpath:path withintermediatedirectories:yes Attributes:nil error:&ERROR]; <5> Copy files/Catalogue//directory and directory copy[Filemanger copyitematpath:fromfilepath topath:todirpath Error:&ERROR]; //file and file copy[Filemanger copyitematpath:fromfilepath topath:tofilepath Error:&ERROR]; <6> Moving files/Catalogue [Filemanger Moveitematpath:frompath Topath:topath Error:nil];<7> Delete files/Catalogue [Filemanger Removeitematpath:topath Error:nil];<8>get file Properties Nsdictionary*attributes =[Filemanger Attributesofitematpath:path Error:nil]; NSLog (@"file properties:%@", attributes); 

2.2 NSData (binary data)

<1> convert NSString to NSData

NSData *data = [string datausingencoding:

Nsutf8stringencoding]

<2> convert NSData to NSString

nsstring *convertstring = [[NSString alloc]

Initwithdata:data Encoding:nsutf8stringencoding]

2.3 nsfilehandle(file handle Class)

To read and write to a file requires Nsfilehandle to open the file first.

Nsfilehandle Read and write to a file are binary data of the NSData type.

<1>Open File Method//read-only handleNsfilehandle*readonlyhandle =[Nsfilehandle Filehandleforreadingatpath:path]; //write-only handleNsfilehandle*writeonlyhandle =[Nsfilehandle Filehandleforwritingatpath:path]; //Read and write handlesNsfilehandle*readandwritehandle =[Nsfilehandle Filehandleforupdatingatpath:path]; <2>reads the specified length of data (in bytes)//read 5 bytes of dataNSData*data = [Readonlyhandle readdataoflength:5]; <3>reads from the current offset to the end of the file [Readonlyhandle readdatatoendoffile][readandwritehandle Readdatatoendoffile]<4>set file offset (in bytes)  [Readonlyhandle seektofileoffset: Number of bytes shifted]; <5>position the file offset to the end of the file [Readonlyhandle Seektoendoffile]; <6>Write the file (you need to set the offset when not overwriting)//1. First point the offset to the end of the file[Readandwritehandle Seektoendoffile]; //2. Write to the specified path[Readandwritehandle writedata:[@"abcdef"Datausingencoding:nsutf8stringencoding]]; <7>Close file handle//closes the file handle, closes it (not required) and can no longer manipulate the file.[Readandwritehandle CloseFile]; [Readonlyhandle CloseFile]; [Writeonlyhandle CloseFile];

3 Plist

<1> What is a plist file, the role of plist file

1.plist File: Property list file, the contents of the file can only be the object contents of the Nsstring,nsnumber,nsdate,nsdata,nsarray,nsdictionary class, cannot save other types of data

2. Role: Persistent storage of some login registration information or program configuration information (small data)

<2> How to create a plist file, how to edit the plist file

The format of the Plist file content is the XML syntax format

1.Xcode creation

1. Right-click->new File Popup dialog box

2.iOS Program Select the resource or Mac program in the iOS bar to select resource in the OS X bar

3. Click the property list in resource to create the plist file

4. Click ' + ' in the file to add data

2. Code creation

If you want to write NSString nsnumber nsdate nsdata nsarray nsdictionary object to the file generally use the plist file

We need to save this data in an array or dictionary, and then call the array and dictionary related functions to write a set of Nsarray or dictionary nsdictionary to the plist file .

Nsarray and Nsdictionary writing file methods

-(BOOL) WriteToFile: (NSString *) path atomically:

(BOOL) Useauxiliaryfile;

<3> How to read plist file data in a program

The root node of the plist file (the outermost layer of the data) is usually an array or dictionary

If the root node of the plist file is a dictionary then use the Dictionary class method

+ (ID) dictionarywithcontentsoffile: (NSString *) path;

Read and write plist files

If the root node is an array then use the class method of the array

+ (ID) arraywithcontentsoffile: (NSString *) path;

Read the plist file.

Note: The above two methods can only read the plist file and cannot read files in other formats.

iOS Development-File operations

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.