iOS-应用程序沙盒机制(SandBox)

iOS应用程序沙盒

iOS程序的沙盒机制SandBox,是一种安全机制,它规定了应用程序只能在为该应用建立的文件夹内读取文件,不能够访问其余地方的内容。 全部的非代码文件都保存在这个地方,好比图片、声音、属性列表和文本文件等。html

(1) 每一个应用程序都在本身的沙盒内,都有独立的文件系统
(2) 不能随意跨越本身的沙盒去访问别的应用程序沙盒中的内容
(3) 应用程序向外请求或接收数据都须要通过权限认证swift

应用程序的目录

默认状况下,每一个沙盒有三个文件夹,Documents、Library、tmp缓存

Documents,苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录;
Library,存储程序的默认设置或其它状态信息;
Library/Caches:存放缓存文件。iTunes不会备份此目录,此目录下文件不会在应用退出删除;
Library/Preferences: 存储程序的默认设置。基于NSUserDefaults的首选项设置便存储在这个里。
tmp,建立和存放临时文件的地方,iTunes备份和恢复的时候不会包括此目录。安全

代码示例:app

//
//  ViewController.swift
//  
import UIKit

class RootViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // 1 Home 目录,即沙河目录 ~/
        let path1 = NSHomeDirectory();
        print("path1 = \(path1)")

        // 2 Documents 目录  ~/Documents
        let path2 = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, false).first!
        print("path2 = \(path2)")

        // 3 Library 目录  ~/Library
        let path3 = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true).first!
        print("path3 = \(path3)")

        // 4 Caches 目录 ~/Library/Caches
        let path4 = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
        print("path4 = \(path4)")

        // 5 tmp 目录 ~/tmp/
        let path5 = NSTemporaryDirectory()
        print("path5 = \(path5)")

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

参考

https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW2ide

http://blog.csdn.net/wzzvictory/article/details/18269713ui

相关文章
相关标签/搜索