iOS learning iOS sandbox (sandbox) mechanism and file operations

Source: Internet
Author: User
Tags create directory

Directory:

iOS learning iOS sandbox (sandbox) mechanism and file operations (i)

iOS learning iOS sandbox (sandbox) mechanism and file Operations (ii)

iOS learning iOS sandbox (sandbox) mechanism and file operation Nsfilemanager (iii)

iOS learning iOS sandbox (sandbox) mechanism and file operations (i)

1. iOS sandbox mechanism

iOS applications can only read files in the file system created for the program, not access to other places, this area is a sandbox, so all non-code files to be stored in this, such as icons, sounds, images, attributes list, text files and so on.

1.1. Each application has its own storage space

1.2, the application can not turn over their walls to access the contents of other storage space

1.3, the application requests the data to pass the permission detection, if does not meet the condition, will not be released.

This diagram can only be understood from the surface of the sandbox is a security system, all the operations of the application through the system to execute, the core content is: Sandbox the application to perform various operations of the permission restrictions.

2. Open the emulator sandbox directory

Here's a look at where the emulator's sandbox folder is on your Mac computer.

The files are in a hidden folder under the personal User name folder, the Chinese is called the Repository, his directory is actually the library.

2.1 Method 1, you can set the display hidden files, and then open directly under the Finder. Here's how to set up viewing hidden files: Open terminal, enter name

command to display Mac hidden files: Defaults write Com.apple.finder appleshowallfiles-bool true

command to hide Mac hidden files: Defaults write Com.apple.finder Appleshowallfiles-bool false

After you lose, click Enter to exit the terminal,

Restart Finder: Click the Apple icon in the upper-left corner of the window to force exit-->finder-->

You can now see the repository folder.

Locate the/application Support/iphone simulator/folder after opening the repository. This is the sandbox directory of the simulator's various programs.

2.2 Method 2, this method is more convenient, on the Finder point-to go to the folder, enter/users/username/library/application Support/iphone simulator/to go.

Username here to write your user name.

3. Directory structure

By default, each sandbox contains 3 folders: Documents, Library, and TMP. Applications can only read and write files in several directories because of the sandboxed mechanism applied

Documents: Apple recommends that file data that is created in the program or browsed in the program be saved in this directory, which is included in itunes backup and restore

Library: The default settings or other status information of the stored program;

Library/caches: Store cached files, itunes does not back up this directory, files in this directory will not be deleted in the app exit

TMP: Provides a place to create temporary files on the fly.

itunes backs up all documents and library files while syncing with the iphone.

When the iphone restarts, all of the TMP files are discarded.

We create a Iossandbox project to expand the practice of sandbox and file read and write operations.

After creation, locate the corresponding directory on the emulator,

This is the catalogue all expanded.

Here are the three directories mentioned above: Documents, Library, tmp

The following article describes directory path fetching and file operations

iOS learning iOS sandbox (sandbox) mechanism and file Operations (ii)

Let's see how to get the application sandbox directory. The directory that includes the sandbox for the real machine.

1, get the program's home directory

    NSString *homedirectory = Nshomedirectory ();    NSLog (@ "path:%@", homedirectory);

Printing results:

2012-06-17 14:00:06.098 iossandbox[3536:f803]/users/rongfzh/library/application Support/iPhone SIMULATOR/5.1/ Applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2

What about the catalogue on the real machine? Let's see.

2012-06-17 14:25:47.059 iossandbox[4281:f803]/var/mobile/applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2

It can be seen that the directory on the real machine is/var/mobile/applications/this directory, and the emulator is not the same. This is the home directory, and the other subdirectories are the same as the emulator.

2. Get the document Directory

    Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *path = [Paths objectatindex:0];    

Print results

2012-06-17 14:00:06.099 iossandbox[3536:f803] path:/users/rongfzh/library/application Support/iPhone SIMULATOR/5.1/ Applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2/documents

3. Get the Cache directory

    Nsarray *paths = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);    NSString *path = [Paths objectatindex:0];    NSLog (@ "%@", Path);

Printing results:

2012-06-17 14:03:50.431 iossandbox[3628:f803]/users/rongfzh/library/application Support/iPhone SIMULATOR/5.1/ Applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2/library/caches

4. Get the Library directory

    Nsarray *paths = Nssearchpathfordirectoriesindomains (Nslibrarydirectory, Nsuserdomainmask, YES);    NSString *path = [Paths objectatindex:0];    NSLog (@ "%@", Path);

Printing results:

2012-06-17 14:07:17.544 iossandbox[3733:f803]/users/rongfzh/library/application Support/iPhone SIMULATOR/5.1/ Applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2/library

5. Get the TMP directory

   NSString *tmpdir = Nstemporarydirectory ();    NSLog (@ "%@", TmpDir);

Printing results:

2012-06-17 14:08:07.824 iossandbox[3782:f803]/var/folders/g7/246bh79130zblw0yjjtc55cw0000gn/t/

6. Writing files

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *docdir = [Paths objectatindex:0];    if (!docdir) {        NSLog (@ "Documents directory not Found");            }    Nsarray *array = [[Nsarray alloc] initwithobjects:@ "Contents", @ "content", nil];    NSString *filepath = [Docdir stringbyappendingpathcomponent:@ "TestFile.txt"];    [Array Writetofile:filepath atomically:yes];

Note: We also run on the real machine, write the file, and then read the content from the real machine.

Write input array, inside is two strings, one will read out to print.

Write us in the program sandbox directory to see the file TestFile.txt

Open the file see the content is this, is an XML format of the plist file, the data format to save the content.

7. Read the file

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *docdir = [Paths objectatindex:0];    NSString *filepath = [Docdir stringbyappendingpathcomponent:@ "TestFile.txt"];    Nsarray *array = [[Nsarray alloc]initwithcontentsoffile:filepath];    NSLog (@ "%@", array);

Printing results:

After parsing the above file, the contents are printed out.

2012-06-17 14:14:46.249 iossandbox[3918:f803] (    "\U5185\U5BB9",    

Read and print the file path on the real machine:

2012-06-17 14:25:47.059 iossandbox[4281:f803]/var/mobile/applications/3b8ec78a-5eee-4c2f-b0cb-4c3f02b996d2/ Documents/testfile.txt

(

"\u5185\u5bb9",

Content

)

can also be written and printed on a real machine.

iOS learning iOS sandbox (sandbox) mechanism and file operation Nsfilemanager (iii)

Let's see how Nsfilemanager is used. This includes creating files, directories, deletions, traversing directories, and so on.

1. Create a directory in documents

Create a directory called Test, first find the documents directory,

Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);      NSString *documentsdirectory = [Paths objectatindex:0];      NSLog (@ "documentsdirectory%@", documentsdirectory);      Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];      NSString *testdirectory = [documentsdirectory stringbyappendingpathcomponent:@ "test"];      Create directory    [filemanager createdirectoryatpath:testdirectory withintermediatedirectories:yes attributes:nil Error: NIL];

Start the program when the directory is created:

2. Create a file in the test directory

What about creating a file? Then the above code Testpath to use stringByAppendingPathComponent stitching on the file name you want to generate, such as Test00.txt. This will make it possible to write to the file under test.

Testdirectory is the path to the above code generation Oh, don't forget. I wrote three files to the test folder, Test00.txt, Test22.txt,text.33.txt. Content is written to content, write String.

The implementation code is as follows:

NSString *testpath = [testdirectory stringbyappendingpathcomponent:@ "Test00.txt"];  NSString *testpath2 = [testdirectory stringbyappendingpathcomponent:@ "Test22.txt"];  NSString *testpath3 = [testdirectory stringbyappendingpathcomponent:@ "Test33.txt"];      NSString *string = @ "Write content, write string"; [FileManager Createfileatpath:testpath contents:[string  datausingencoding:nsutf8stringencoding] Attributes: NIL]; [FileManager createfileatpath:testpath2 contents:[string  datausingencoding:nsutf8stringencoding] Attributes: NIL]; [FileManager createfileatpath:testpath3 contents:[string  datausingencoding:nsutf8stringencoding] Attributes: NIL];

Look at the following figure, three files are out, the content is also right.

It's even easier to create it in the documents directory, without adding test.

3. Get all the file names in the directory column

Two ways to get: Subpathsofdirectoryatpath and Subpathsatpath

    Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);      NSString *documentsdirectory = [Paths objectatindex:0];      NSLog (@ "documentsdirectory%@", documentsdirectory);      Nsfilemanager *filemanage = [Nsfilemanager Defaultmanager];      NSString *mydirectory = [documentsdirectory stringbyappendingpathcomponent:@ "test"];      Nsarray *file = [Filemanage subpathsofdirectoryatpath:mydirectory error:nil];     NSLog (@ "%@", file);      Nsarray *files = [Filemanage subpathsatpath:mydirectory];     

Get the file name in the test folder just above

Print results

2012-06-17 23:23:19.684 iossandbox[947:f803] fileList: (    ". Ds_store ",    " Test00.txt ",    " Test22.txt ",    " Test33.txt ") 2012-06-17 23:23:19.686 iossandbox[947:f803] Filelit (    ". Ds_store ",    " Test00.txt ",    " Test22.txt ",    " Test33.txt ")

Two methods are available, hidden files are also printed out.

4. FileManager Use operation current directory

Create File Manager    Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];    Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);    NSString *documentsdirectory = [Paths objectatindex:0];    Change to the directory under Operation    [FileManager changecurrentdirectorypath:[documentsdirectory Stringbyexpandingtildeinpath];    Create file FileName File name, contents file contents, if Start no content can be set to Nil,attributes file properties, initially nil    nsstring * fileName = @ " TestFileNSFileManager.txt ";    Nsarray *array = [[Nsarray alloc] initwithobjects:@ "Hello World", @ "Hello world1", @ "Hello world2", nil];    [FileManager createfileatpath:filename Contents:array Attributes:nil];

This creates the TestFileNSFileManager.txt and writes three Hello world to the file.

Changecurrentdirectorypath directory changes to the current operating directory, do the file read and write is very convenient, do not add full path

5. Delete Files

After the code above, remove is OK.

[FileManager Removeitematpath:filename Error:nil];

6. Mixed data reading and writing

Create mixed data with nsmutabledata and then write to the file. and read the data according to the type of data.

6.1 Write Data:

nsstring * fileName = @" TestFileNSFileManager.txt "; Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString *documentsdirectory = [Paths objectatindex:0]; Get file path NSString *path = [Documentsdirectory stringbyappendingpathcomponent:filename]; Data to be written nsstring *temp = @ "Nihao World"; int dataint = 1234; float datafloat = 3.14f; Create Data buffer Nsmutabledata *writer = [[Nsmutabledata alloc] init]; Add a string to the buffer [writer Appenddata:[temp datausingencoding:nsutf8stringencoding]]; Add additional data to the buffer [writer Appendbytes:&dataint length:sizeof (dataint)]; [Writer Appendbytes:&datafloat length:sizeof (datafloat)]; Writes buffered data to a file [writer Writetofile:path Atomically:yes];

Let's see how the data looks:

We see the back is garbled, it is Chinese was turned into a nsdata, and the binary of int float

6.2 Read the data just written:

Read data:    int intdata;    float floatdata = 0.0;    NSString *stringdata;        NSData *reader = [NSData Datawithcontentsoffile:path];    StringData = [[NSString alloc] Initwithdata:[reader subdatawithrange:nsmakerange (0, [temp length])]                                   encoding: Nsutf8stringencoding];    [Reader Getbytes:&intdata range:nsmakerange ([temp length], sizeof (Intdata))];    [Reader Getbytes:&floatdata range:nsmakerange ([temp length] + sizeof (intdata), sizeof (Floatdata))];    NSLog (@ "stringdata:%@ intdata:%d floatdata:%f", StringData, Intdata, Floatdata);

Print out the results:

2012-06-17 23:51:14.723 iossandbox[1285:f803] Stringdata:nihao hello! intdata:1234332 floatdata:3.140000

Here the written characters are changed to Hello. Because [temp length] is the length of the calculation, the Chinese is counted as one, the result is wrong.

iOS learning iOS sandbox (sandbox) mechanism and file operations

Related Article

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.