简体   繁体   English

'stringByAppendingPathComponent'不可用

[英]'stringByAppendingPathComponent' is unavailable

I'm getting the error 我收到了错误

'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead.

when I try to do 当我尝试做的时候

let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite")

This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5. 这显然对以前的人有用,但现在在Xcode 7 beta 5中对我不起作用。

This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to NSString . Apple Developer论坛上的这个主题有建议使用扩展或直接转换为NSString But if I do convert it to an NSString 但是,如果我将它转换为NSString

let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString)

then I get the error 然后我得到了错误

'NSString' is not implicitly convertible to 'String'...

and it gives me the option to "fix-it" by inserting as String , which brings us back to the original error. 它通过插入as String给我选择“修复它”,这使我们回到原始错误。

This also happens for stringByAppendingPathExtension . stringByAppendingPathExtension也会发生这种情况。

What do I do? 我该怎么办?

You can create a URL rather rather than a String path. 您可以创建URL而不是String路径。

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileURL = documentsURL?.appendingPathComponent("test.sqlite")

If you absolutely need the path, then you can get it like this: 如果你绝对需要路径,那么你可以这样得到它:

guard let path = fileURL?.path else {
    return
}

print(path) // path will exist at this point

There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths. 在您提到的主题中有一些讨论,Apple可能会故意指导人们使用URL而不是String路径。

See also: 也可以看看:

您可以使用:

let dbPath = (documentsFolder as NSString).stringByAppendingPathComponent("db.sqlite")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM