IOS 開發(fā)之數(shù)據(jù)存儲writeToFile的應(yīng)用實例
最近項目上要弄數(shù)據(jù)的導(dǎo)入與導(dǎo)出,所以就研究了一下數(shù)據(jù)的保存,其實很簡單
第一步:獲得文件即將保存的路徑:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);//使用C函數(shù)NSSearchPathForDirectoriesInDomains來獲得沙盒中目錄的全路徑。該函數(shù)有三個參數(shù),目錄類型、he domain mask、布爾值。其中布爾值表示是否需要通過~擴展路徑。而且第一個參數(shù)是不變的,即為NSSearchPathDirectory 。在iOS中后兩個參數(shù)也是不變的,即為:NSUserDomainMask 和 YES。
NSString *ourDocumentPath =[documentPaths objectAtIndex:0];
還有一種方法是使用NSHomeDirectory函數(shù)獲得sandbox的路徑。具體的用法為:
NSString *sandboxPath = NSHomeDirectory();
// Once you have the full sandbox path, you can create a path from it,但是不能在sandbox的本文件層上寫文件也不能創(chuàng)建目錄,而應(yīng)該是此基礎(chǔ)上創(chuàng)建一個新的可寫的目錄,例如Documents,Library或者temp。
NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];//將Documents添加到sandbox路徑上,具體原因前面分析了!
這兩者的區(qū)別就是:使用NSSearchPathForDirectoriesInDomains比在NSHomeDirectory后面添加Document更加安全。因為該文件目錄可能在未來發(fā)送的系統(tǒng)上發(fā)生改變。
第二步:生成在該路徑下的文件:
NSString *FileName=[documentPath stringByAppendingPathComponent:fileName];//fileName就是保存文件的文件名
第三步:往文件中寫入數(shù)據(jù):
[data writeToFile:FileName atomically:YES];//將NSData類型對象data寫入文件,文件名為FileName
最后:從文件中讀出數(shù)據(jù):
NSData *data=[NSData dataWithContentsOfFile:FileName options:0 error:NULL];//從FileName中讀取出數(shù)據(jù)
以上就是IOS 開發(fā)之數(shù)據(jù)存儲writeToFile的應(yīng)用實例,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答