Checklists学习日志之建立存储文件用的地址

来源:互联网 发布:windows hadoop 2.7.0 编辑:程序博客网 时间:2024/05/16 19:41

    iOS中如果不可以存储数据的话产生的数据会留在进程中,一旦程序被关闭则数据消失,所以需要将要存储的数据放在专用的空间进行存储。首先获取文件夹的地址,如下:

    func documentsDirectory()-> String        // get the path to the Documents folder    {        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)        // 三个参数        // 1.DocumentDirectory:Document directory        // 2.The user’s home directory—the place to install user’s personal items (~).        // 3.expandTilde 是否展开成完整路径。如果展开,调用stringByExpandingTildeInPath函数        print("\(paths)")        print("\(paths[0])")        return paths[0]    }

</pre>    这里用到了NSSearchPathForDirectoriesInDomains函数,它有三个输入变量:1. DocumentDirectory; 2. UserDomainMask,即user’s home directory,也即APP的安装地址; 3.expandTilde,布尔类型变量,如果true,则调用stringByExpandingTildeInPath函数展开成完整的地址,如果为false,保持缩写地址,一般为“~” or “~user” 。我们看到,输出的paths为["/Users/longrain/Library/Developer/CoreSimulator/Devices/05FA3182-5BE0-4732-856D-E3871934E6C7/data/Containers/Data/Application/5ECDFD23-2D3D-4284-903A-58EF18FFF58E/Documents"],是一个数组,输出的paths[0]为/Users/longrain/Library/Developer/CoreSimulator/Devices/05FA3182-5BE0-4732-856D-E3871934E6C7/data/Containers/Data/Application/5ECDFD23-2D3D-4284-903A-58EF18FFF58E/Documents,是一个字符串。</p><p>        获取到文件夹地址后,我们要获取用于存储数据的文件的地址:</p><p><pre name="code" class="objc">    func dataFilePath() -> String        // construct the full path to the file that will store the checklist items.    {        let directory = documentsDirectory() as NSString        return directory.stringByAppendingPathComponent("/Checklists.plist")//        return (documentsDirectory() as NSString).stringByAppendingPathComponent("Checklists.plist")    }

    这里的stringByAppendingPathComponent函数,Returns a new string made by appending to the receiver a given string. 在directory后加上Checklists.plist,所以路径变成/Users/longrain/Library/Developer/CoreSimulator/Devices/05FA3182-5BE0-4732-856D-E3871934E6C7/data/Containers/Data/Application/5ECDFD23-2D3D-4284-903A-58EF18FFF58E/Documents/Checklists.plist。值得注意的是,比如需要加的字符是“scratch.tiff”,则

Receiver’s String Value

Resulting String

/tmp

/tmp/scratch.tiff

/tmp/

/tmp/scratch.tiff

/

/scratch.tiff

“” (an empty string)

scratch.tiff

所以,"/Checklists.plist"中的/,可以要也可以不要。

0 0
原创粉丝点击