3 回答

TA貢獻1802條經驗 獲得超4個贊
顯然,編譯器認為NSSearchPathDirectory:0是一個數組,并且當然希望使用該類型NSSearchPathDirectory。當然不是有用的錯誤消息。
但至于原因:
首先,您混淆了參數名稱和類型??匆幌潞瘮刀x:
func NSSearchPathForDirectoriesInDomains(
directory: NSSearchPathDirectory,
domainMask: NSSearchPathDomainMask,
expandTilde: Bool) -> AnyObject[]!
directory并且domainMask是名稱,您正在使用類型,但是無論如何您都應該將它們留給函數使用。它們主要用于方法中。
另外,Swift是強類型的,因此您不應僅使用0。而應使用枚舉的值。
最后,它返回一個數組,而不僅僅是一個路徑。
因此,我們有了(針對Swift 2.0更新):
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
對于Swift 3:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

TA貢獻1797條經驗 獲得超6個贊
現代建議是將NSURL用于文件和目錄,而不是基于NSString的路徑:
因此,以NSURL的形式獲取應用程序的Document目錄:
func databaseURL() -> NSURL? {
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectory: NSURL = urls.first as? NSURL {
// This is where the database should be in the documents directory
let finalDatabaseURL = documentDirectory.URLByAppendingPathComponent("items.db")
if finalDatabaseURL.checkResourceIsReachableAndReturnError(nil) {
// The file already exists, so just return the URL
return finalDatabaseURL
} else {
// Copy the initial file from the application bundle to the documents directory
if let bundleURL = NSBundle.mainBundle().URLForResource("items", withExtension: "db") {
let success = fileManager.copyItemAtURL(bundleURL, toURL: finalDatabaseURL, error: nil)
if success {
return finalDatabaseURL
} else {
println("Couldn't copy file to final location!")
}
} else {
println("Couldn't find initial database in the bundle!")
}
}
} else {
println("Couldn't get documents directory!")
}
return nil
}
這具有基本的錯誤處理能力,因為這種情況取決于您的應用程序在這種情況下將執行的操作。但這使用文件URL和更現代的api返回數據庫URL,如果捆綁包中不存在初始版本,則將其從副本包中復制出來;如果發生錯誤,則將其復制為nil。
- 3 回答
- 0 關注
- 867 瀏覽
添加回答
舉報