亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Swift中找到NSDocumentDirectory?

如何在Swift中找到NSDocumentDirectory?

侃侃無極 2019-12-13 09:13:45
我正在嘗試使用代碼獲取Documents文件夾的路徑:var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)但是Xcode給出了錯誤: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'我試圖了解代碼中的錯誤。
查看完整描述

3 回答

?
慕虎7371278

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]


查看完整回答
反對 回復 2019-12-13
?
互換的青春

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。


查看完整回答
反對 回復 2019-12-13
  • 3 回答
  • 0 關注
  • 867 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號