//转载:http://www.helloswift.com.cn/swiftmanual/2015/0208/3486.html
应用沙盒结构分析
1、应用程序包:包含了所有的资源文件和可执行文件
2、Documents:保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录
3、tmp:保存应用运行时所需要的临时数据,使用完毕后再将相应的文件从该目录删除。应用没有运行,系统也可能会清除该目录下的文件,iTunes不会同步备份该目录
4、Library/Cache:保存应用运行时生成的需要持久化的数据,iTunes同步设备时不备份该目录。一般存放体积大、不需要备份的非重要数据
5、Library/Preference:保存应用的所有偏好设置,IOS的Settings应用会在该目录中查找应用的设置信息。iTunes同步设备时会备份该目录
IOS中的数据存储
1、存储为plist属性列表
- func saveWithFile() {
- /// 1、获得沙盒的根路径
- let home = NSHomeDirectory() as NSString;
- /// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
- let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
- /// 3、获取文本文件路径
- let filePath = docPath.stringByAppendingPathComponent("data.plist");
- var dataSource = NSMutableArray();
- dataSource.addObject("衣带渐宽终不悔");
- dataSource.addObject("为伊消得人憔悴");
- dataSource.addObject("故国不堪回首明月中");
- dataSource.addObject("人生若只如初见");
- dataSource.addObject("暮然回首,那人却在灯火阑珊处");
- // 4、将数据写入文件中
- dataSource.writeToFile(filePath, atomically: true);
- println("\(filePath)");
- }
- func readWithFile() {
- /// 1、获得沙盒的根路径
- let home = NSHomeDirectory() as NSString;
- /// 2、获得Documents路径,使用NSString对象的stringByAppendingPathComponent()方法拼接路径
- let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
- /// 3、获取文本文件路径
- let filePath = docPath.stringByAppendingPathComponent("data.plist");
- let dataSource = NSArray(contentsOfFile: filePath);
- println("\(dataSource)");
- }
2、使用NSUserDefaults存储数据
- func saveWithNSUserDefaults() {
- /// 1、利用NSUserDefaults存储数据
- let defaults = NSUserDefaults.standardUserDefaults();
- // 2、存储数据
- defaults.setObject("衣带渐宽终不悔", forKey: "name");
- // 3、同步数据
- defaults.synchronize();
- }
- func readWithNSUserDefaults() {
- let defaults = NSUserDefaults.standardUserDefaults();
- let name = defaults.objectForKey("name") as NSString;
- println("\(name)");
- }
3、归档存储:对象需要实现NSCoding协议,归档对应encode,反归档对应decode
- /**
- 归档数据
- 需要实现NSCoding协议
- */
- func saveWithNSKeyedArchiver() {
- let home = NSHomeDirectory() as NSString;
- let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
- let filePath = docPath.stringByAppendingPathComponent("book.data");
- let book = CFAddressBook(name: "Francis", call: "199");
- /**
- * 数据归档处理
- */
- NSKeyedArchiver.archiveRootObject(book, toFile: filePath);
- }
- /**
- 反归档数据
- */
- func readWithNSKeyedUnarchiver() {
- let home = NSHomeDirectory() as NSString;
- let docPath = home.stringByAppendingPathComponent("Documents") as NSString;
- let filePath = docPath.stringByAppendingPathComponent("book.data");
- let book = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as CFAddressBook;
- println("\(book.name), \(book.call)");
- }
4、SQlite3
5、CoreData