为什么在viewDidLoad()之外的初始化失败? [英] Why does initialisation outside of `viewDidLoad()` fail?

查看:76
本文介绍了为什么在viewDidLoad()之外的初始化失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法编译:

class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {

    let fileManager = NSFileManager.defaultManager()

    let dir: NSURL? = NSURL.fileURLWithPath("/Users/wilfred/")

    var error: NSError? = nil

    var folderContents: [NSURL]? = fileManager.contentsOfDirectoryAtURL(dir!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions(), error: &error) as [NSURL]?

…但是这样做:

class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {

    let fileManager = NSFileManager.defaultManager()

    let dir: NSURL? = NSURL.fileURLWithPath("/Users/wilfred/")

    var error: NSError? = nil

    var folderContents: [NSURL]? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        self.folderContents =  fileManager.contentsOfDirectoryAtURL(dir!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions(), error: &error) as [NSURL]?
    }

并且请注意,我只从声明块中取出了用于初始化folderContents的块,并将其复制到了viewDidLoad()块中.为什么!?!?!

And notice that I only took the block for initialising folderContents from the declaration block and copied it over to the viewDidLoad() block. Why!?!?!

我得到的错误是:

…对我来说似乎是伪造的.

… which seems bogus to me.

推荐答案

属性是在创建self之前初始化的,因此,当您想在folderContents中获取fileManager时,该文件为self.fileManager,self不存在,所以你无法获得自我的任何特性. 例如,如果您重写任何类的init方法,在其中放置一个断点,然后在属性上设置断点,然后执行代码,则可以看到属性是最先到达的,而不是init.

Properties are initialized before self is created, so when you want to get fileManager in folderContents, which is self.fileManager, self is not existing, so you can't get any property of self. If you for example override the init method of any class, put a breakpoint in there and breakpoint to the properties, execute the code, you can see that the properties reached first, not the init.

这篇关于为什么在viewDidLoad()之外的初始化失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆