如何在Swift中找到NSDocumentDirectory?

我正在尝试使用代码获取Documents文件夹的路径:


var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true)

但是Xcode给出了错误: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory'


我试图了解代码中的错误。


侃侃无极
浏览 746回答 3
3回答

慕虎7371278

显然,编译器认为NSSearchPathDirectory:0是一个数组,并且当然希望使用该类型NSSearchPathDirectory。当然不是有用的错误消息。但至于原因:首先,您混淆了参数名称和类型。看一下函数定义: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]

互换的青春

现代建议是将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。
打开App,查看更多内容
随时随地看视频慕课网APP