加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – ‘在super.init初始化self之前在方法调用中使用self’,

发布时间:2020-12-14 05:44:31 所属栏目:百科 来源:网络整理
导读:我很好奇是无论如何都要在init方法中调用一个方法来设置类的实例属性.基本上我只有一个子类UIView的类,在init中添加一些子视图,其中一些子视图是类的实例变量. class MyView: UIView { var collectionView: UICollectionView convenience init () { self.ini
我很好奇是无论如何都要在init方法中调用一个方法来设置类的实例属性.基本上我只有一个子类UIView的类,在init中添加一些子视图,其中一些子视图是类的实例变量.
class MyView: UIView {
    var collectionView: UICollectionView

    convenience init () {
        self.init(frame:CGRectZero)
    }

    override init (frame : CGRect) {
        super.init(frame : frame)

        addSubviews()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        addSubviews()
    }

    func addSubviews (){
        self.collectionView = UICollectionView()

    }
}

现在的问题是我在初始化类内部属性之前不能调用super init(属性’self.collectionView’在super.init调用时没有被初始化),但是我也无法调用我的自定义方法来初始化那些变量super.init,因为它不能在初始化之前使用self.我意识到我可以使实例变量可选,但它似乎不太优雅,因为我知道它将始终被初始化(还有几个,这只是一个简化版本).有没有办法在不制作所有实例变量选项的情况下完成此操作?

编辑:

我想最终我的问题是为什么swift dis-allow在调用super.init之前调用一个方法?有什么区别:

override init (frame : CGRect) {
    addSubviews()
    super.init(frame : frame)
}

final func addSubviews (){
    self.collectionView = UICollectionView()
}

override init (frame : CGRect) {
    self.collectionView = UICollectionView()
    super.init(frame : frame)
}
表格文件:

Swift’s compiler performs four helpful safety-checks to make sure that
two-phase initialization is completed without error:

Safety check 1 A designated initializer must ensure that all of the
properties introduced by its class are initialized before it delegates
up to a superclass initializer.

在调用super.init()之前,需要为实例变量设置值.在此操作之后,您将访问调用实例方法.在你的情况下,你可以这样做:

override init (frame : CGRect) {
    self.collectionView = UICollectionView()
    super.init(frame : frame)
    // Now you can call method
    self.someMethod()
}

ADD for question’s EDIT:

由于安全原因,您无法在super.init()调用之前调用方法.如果你这样做,那么你的方法可以使用一些尚未在父类中初始化的属性

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读