標籤:
應用沙箱結構分析
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
Swift之沙箱與資料存放區