IOS sandbox mechanism and file operations

Source: Internet
Author: User

This article see the introduction of http://www.uml.org.cn/mobiledev/201209211.asp#1 in this article, respect for the original.


1. iOS sandbox Mechanism

IOS applications can only read files from the file system created in this application. They cannot be accessed from other places. This area is a sandbox, all non-code files must be stored here, such as icons, sounds, images, attribute lists, and text files.

1.1. Each application has its own storage space.

1.2. applications cannot access the content of other buckets through their own walls.

1.3. The data requested by the application must pass permission detection. If the data does not meet the conditions, it will not be released.

Through this figure, we can only understand from the surface that sandbox is a security system. All operations of an application must be performed through this system. The core content of this system is: sandbox has the permission to perform various operations on the application.


2. Open the sandbox directory of the simulator.

Next let's take a look at the location of the sandbox folder of the simulator on Mac.

Files are stored in a hidden folder under the personal username folder. The Chinese name is the resource library, and the English name is the library.

The following describes a simple method to go To the folder: click on the finder> go to the folder



After entering the simulator, it contains the sandbox of each application.

Enter an application, such as a sandbox.

The following describes the directory structure of a sandbox:

By default, each sandbox contains three folders: Documents, library, TMP, and an application file (also a file ). Because of the sandbox mechanism of the application, the application can only read and write files under several directories.

Documents: Apple recommends that you store the file data created or browsed in the program in this directory. This directory will be included during iTunes backup and recovery.

Library: the default setting of the storage program or other status information;

Library/caches: stores cached files. iTunes will not back up this directory, and files under this directory will not be deleted after the application exits.

TMP: provides a place to create temporary files in real time.

During synchronization with the iPhone, iTunes backs up all documents and library files.

When the iPhone restarts, It discards all TMP files.


Note: It is easy to be confused with bundle here. The following describes the differences between the two based on your understanding:

Bundle: When an iOS application is generated, xcode binds it into a package. A bundle is a directory in a file system. It groups related resources in one place. An iOS app bundle contains executable files and support resource files (such as application icons, image files, and localized content ).

A bundle is a directory with a standardizedhierarchical structure that holds executable code and the resources used by that code.

Therefore, you can regard the entire application as a bundle.

The concept of sandbox is not directly related to bundle. the sandbox only indicates that program resources are isolated from the outside world.


The following is a simple example of bundle and sandbox.


// The newly created plist file is in the application. You can use bundle to access this file nsstring * plistpath = [[nsbundle mainbundle] pathforresource: @ "myplist" oftype: @ "plist"]; nsmutablearray * array = [nsmutablearray arraywithcontentsoffile: plistpath]; // Add a new project to the array [array addobject: @ "3"]; // rewrite bool value = [array writetofile: plistpath atomically: Yes] In the plist file; If (value) {nsmutablearray * newarray = [nsmutablearray arraywithcontentsoffile: plistpath]; nslog (@ "new array = % @", newarray);}/* output: New array = (0, 1, 2, 3) * // obtain the document directory (absolute path) in the sandbox nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * documentsdirectory = [paths objectatindex: 0]; nsstring * newpath = [documentsdirectory stringbyappendingpathcomponent: @ "data. plist "]; // write the array to the data in the document of the sandbox. in the plist file, [array writetofile: newpath atomically: Yes]; nsmutablearray * arr = [[nsmutablearray alloc] initwithcontentsoffile: newpath]; nslog (@ "array in data. plist = % @ ", arr);/* output: array in data. plist = (0, 1, 2, 3 )*/


Note: We first create a plist file in the project (the root type is an array) and add three elements. Because the newly created plist file is in the application, we can get the plist file through bundle, read the array, add a data element, and write it back to the plist file. Then we get the directory of the sandbox document and write the file to the data in the sandbox. plist file (if it does not exist, a new one will be automatically created), and then from data. plist read this array.

About the newly created myplist. plist file. We added a new element to the array written back to the file, but we can view this myplist in xcode. the plist file does not show the newly added array elements, but we can see it in the sandbox. This estimation is a problem of xoode itself.

You can also view the data. plist file in the document in the sandbox. For example:



3. Obtain the sandbox directory:

// 1. Obtain the program's home directory nsstring * homedirectory = nshomedirectory (); nslog (@ "Path: % @", homedirectory); // path: /users/IOS/library/Application Support/iPhone simulator/6.1/applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671 // 2. Get the document directory nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes ); nsstring * Path = [paths objectatindex: 0]; nslog (@ "Path: % @", PATH); // path: /users/IOS/library/Application Support/iPhone simulator/6.1/applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/Documents // 3. Get the cache directory nsarray * paths = nssearchpathfordirectoriesindomains (nscachesdirectory, nsuserdomainmask, yes ); nsstring * Path = [paths objectatindex: 0]; nslog (@ "Path: % @", PATH); // path: /users/IOS/library/Application Support/iPhone simulator/6.1/applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/library/caches // 4. Get the library directory nsarray * paths = nssearchpathfordirectoriesindomains (nslibrarydirectory, nsuserdomainmask, yes); nsstring * Path = [paths objectatindex: 0]; nslog (@ "Path: % @", PATH); // path: /users/IOS/library/Application Support/iPhone simulator/6.1/applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/library // 5, get tmp directory nsstring * tmpdir = nstemporarydirectory (); nslog (@ "Path: % @", tmpdir); // path:/users/IOS/library/Application Support/iPhone simulator/6.1/applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/tmp/

4,Nsfilemanager for file operations


4.1 create a file directory in document

Nsarray * paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * documentsdirectory = [paths objectatindex: 0]; nslog (@ "documentsdirectory % @", documentsdirectory ); nsfilemanager * filemanager = [nsfilemanager defaultmanager]; nsstring * testdirectory = [documentsdirectory stringbyappendingpathcomponent: @ "test"]; // create a directory [filemanager createdirectoryatpath: testdirectory metadata: Yes attributes: Nil error: nil];


4.2 create a file under the test directory

What should I do when creating a file? Next, use the code testpath to concatenate the file name that you want to generate with stringbyappendingpathcomponent, for example, test11.txt. In this way, files can be written to the test directory.

Testdirectory is the path generated by the code above. Don't forget. I wrote three files to the test folder, test11.txt, test22.txt, and text.33.txt. Write string.

The implementation code is as follows:

Nsstring * testpath1 = [testdirectory stringbyappendingpathcomponent: @ "test1.txt"]; nsstring * testpath2 = [testdirectory stringbyappendingpathcomponent: @ "test2.txt"]; nsstring * testpath3 = [testdirectory Plugin: @ "test3.txt"]; nsstring * string = @ "write content, write string"; [filemanager createfileatpath: testpath1 contents: [String datausingencoding: nsutf8stringencoding] attributes: Nil]; [filemanager createfileatpath: testpath2 contents: [String datausingencoding: encoding] attributes: Nil]; [filemanager createfileatpath: testpath3 contents: [String datausingencoding: encoding] attributes: Nil];

4.3Retrieve all file names in the directory Column

Two Methods: 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"]; // method 1 nsarray * file = [filemanage subpathsofdirectoryatpath: mydirectory error: nil]; nslog (@ "% @", file); // method 2 nsarray * files = [filemanage subpathsatpath: mydirectory]; nslog (@ "% @", files );

Obtain the file name under the test directory:

Both methods are output

(    "test1.txt",    "test2.txt",    "test3.txt")

4.4. Use filemanager to operate the current directory

// Create File Manager nsfilemanager * filemanager = [nsfilemanager defaultmanager]; nsarray * paths = catalog (nsdocumentdirectory, nsuserdomainmask, yes); nsstring * documentsdirectory = [paths objectatindex: 0]; // change to [filemanager changecurrentdirectorypath: [documentsdirectory stringbyexpandingtildeinpath] under the directory to be operated; // create the file filename file name, content of the contents file, if there is no content at the beginning, you can set it to nil, the attribute of the attributes file, initially nil nsstring * filename = @ "testfilensfilemanager.txt"; nsarray * array = [[nsarray alloc] initwithobjects: @ "Hello World", @ "Hello world1", @ "Hello World2", nil]; // convert the array type to nsdata nsmutabledata * Data = [[nsmutabledata alloc] init]; for (INT I = 0; I <[array count]; ++ I) {nsstring * STR = [array objectatindex: I]; nsdata * temp = [STR datausingencoding: nsutf8stringencoding]; [data appenddata: temp];} // note that the contents parameter type is nsdata [filemanager createfileatpath: Filename contents: data attributes: Nil];


4.5 delete an object

Then the code above will delete the newly created testfilensfilemanager.txt file!

    [fileManager removeItemAtPath:fileName error:nil];

4.6 For hybrid Data Reading and Writing, see the final content of the original article.


That's probably so much!


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.