swift中的檔案操作
阿新 • • 發佈:2018-12-25
自從學習了iOS的新語言就感覺一個更加有趣的世界開啟了,它的橫空出世必定會帶來一番腥風血雨。這次就談談Swift中關於檔案的操作,記憶中學習Swift差不多一個月就可以上手些專案了,比較深的體會是它面向物件的語言特徵更加刻骨。有OC基礎的童靴學習Swift是不在話下的,不過它還是有很多強大的東西是你必須花時間去掌握的。這次帶來自己封裝的一個檔案操作的類引擎:
關於檔案判無和路徑的例項方法:
// 在Document路徑下判斷,什麼這裡返回值是可選的字串值呢,這裡可選是因為返回值可能為nil,其他返回值為可選型別的同樣是這個規則。 func localDocumentsPath(fileName:String) ->String?{ return createNeeded(fileName) } // 檔案不存在則建立為 func createNeeded(fileName:String) ->String?{ let fileManage = NSFileManager.defaultManager() let filePath = returnDocumentsPathWithFileName(fileName) if !fileManage.fileExistsAtPath(filePath!){ let bundlePath = NSBundle.mainBundle().resourcePath let defaultFilePath = bundlePath! + "/\(NoteFile)" do{ try fileManage.copyItemAtPath(defaultFilePath, toPath: filePath!) }catch{ print("錯誤寫入檔案!") } } return filePath } // 檔案Document路徑 func returnDocumentsPathWithFileName(fileName:String) ->String?{ let documentDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last let documentPath = "\(documentDir!)/\(fileName)" return documentPath }
兩個靜態方法分別進行檔案的讀和寫,寫的時候在靜態方法中呼叫例項方法會發現調不了,什麼鬼。。。 然後你會思考怎麼調,其實在靜態方法裡可以用很多方式來呼叫例項方法,這裡給出一種方式:
class func readCurrentFile(fileName:String) -> String?{ let currentClassObject = FileManagerEngine() let filePath = currentClassObject.localDocumentsPath(localDataFile) let fileManage = NSFileManager.defaultManager() var content: String? if fileManage.fileExistsAtPath(filePath!){ let tmpData = NSData.init(contentsOfFile: filePath!) content = String.init(data: tmpData!, encoding: NSUTF8StringEncoding) } return content } class func writeNoteToFileWithData(stringData:String) { let currentClassObject = FileManagerEngine() let filePath = currentClassObject.localDocumentsPath(localDataFile) let writeData = NSMutableData.init(contentsOfFile: filePath!) writeData!.appendData(stringData.dataUsingEncoding(NSUTF8StringEncoding)!) writeData!.writeToFile(filePath!, atomically: true) }
可以看出Swift也不怎麼難,重點要掌握其中的核心思想:面向物件,簡潔。