问题描述
我收到错误
'stringByAppendingPathComponent' is unavailable: Use 'stringByAppendingPathComponent' on NSString instead.
当我尝试时
let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite")
这显然对以前的人有用,但现在在Xcode 7 beta 5中对我不起作用。
This apparently worked for people before, but it doesn't work for me now in Xcode 7 beta 5.
建议使用扩展程序或直接转换为 NSString
。但如果我确实将它转换为 NSString
This thread on the Apple Developer Forums had the suggestion to use an extension or do a direct cast to NSString
. But if I do convert it to an NSString
let databasePath = documentsFolder.stringByAppendingPathComponent("test.sqlite" as NSString)
然后我收到错误
'NSString' is not implicitly convertible to 'String'...
它通过插入作为String
给了我修复它的选项,这让我们回到原来的错误。
and it gives me the option to "fix-it" by inserting as String
, which brings us back to the original error.
这也适用于 stringByAppendingPathExtension
。
我该怎么办?
推荐答案
您可以创建一个URL,而不是一个String路径。
You can create a URL rather rather than a String path.
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
您提到Apple可能会故意指导人们使用URL而不是String路径。
There was some discussion in the thread you mentioned that Apple may be purposely guiding people toward using URLs rather than String paths.
参见:
- What's the difference between path and URL in iOS?
- NSFileManager URL vs Path
- Swift 2.0: Why Guard is Better than If
这篇关于'stringByAppendingPathComponent'不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!