我有以下代码:
var myBundle:NSBundle
myBundle = NSBundle.mainBundle() // what is the role of this line ??
if let path = myBundle.pathForResource("CellDescriptor", ofType: "plist"){
var cellDescriptors: NSMutableArray!
cellDescriptors = NSMutableArray(contentsOfFile: path)
}
为什么我要使用这行代码 myBundle = NSBundle.mainBundle()
?我读到它正在初始化 myBundle
对象。但这到底是什么意思?
为什么不初始化 myBundle
对象就不能调用 pathForResource
函数?
谢谢。
最佳答案
让我们逐步考虑这一行:
myBundle = NSBundle.mainBundle()
您声明了类型为 NSBundle 的变量 myBundle。现在您需要使用适当的实例对象初始化此变量。例如,您可以使用构造函数。但是对于某些类,您有“静态构造函数”。如果您没有将变量设置为正确的对象 - 默认情况下它具有 nil 值,因此您无法访问实例方法。
NSBundle.mainBundle()
- 这是对 NSBundle 类(静态方法)的 mainBundle 方法的调用,它返回给您正确的实例(对于这种情况 - 它是您应用程序的主要包。来自文档:
The NSBundle object corresponding to the bundle directory that contains the current executable. This method may return a valid bundle object even for unbundled apps. It may also return nil if the bundle object could not be created, so always check the return value.
希望这对您有所帮助。
关于ios - Swift 中的对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541611/