在Swift中使用所需的init(coder aDecoder:NSCoder)中的方法

时间:2018-03-31 12:41:44

标签: ios swift

我在View Controller中有以下内容:

required init(coder aDecoder: NSCoder) {

    selectedFocusAreas = Array()
    for _ in 0...focusAreas.count {
        selectedFocusAreas.append(false)
    }

    super.init(coder: aDecoder)!

}

此代码编译并没有给我任何问题。但是,当我尝试将代码提取到如下方法中时:

required init(coder aDecoder: NSCoder) {
        setUpSelectedFocusAreaData()
        super.init(coder: aDecoder)!
    }

    func setUpSelectedFocusAreaData(){
        selectedFocusAreas = Array()
        for _ in 0...focusAreas.count {
            selectedFocusAreas.append(false)
        }
    }

我收到以下编译错误:

  • self初始化自我之前在方法调用setUpSelectedFocusAreaData中使用super.init
  • self.selectedFocusAreas来电
  • 时尚未初始化的属性super.init

有没有办法在init方法中调用方法?

1 个答案:

答案 0 :(得分:1)

@ Paulw11是钱,你必须做以下事情:

required init(coder aDecoder: NSCoder) {
        selectedFocusAreas = Array()
        setUpSelectedFocusAreaData()
        super.init(coder: aDecoder)!
    }

    func setUpSelectedFocusAreaData(){
        for _ in 0...focusAreas.count {
            selectedFocusAreas.append(false)
        }
    }

即先初始化该值,然后调用该方法。