“initialize” class method for classes in Swift?

后端 未结 6 1090
日久生厌
日久生厌 2020-12-04 11:55

I\'m looking for behavior similar to Objective-C\'s +(void)initialize class method, in that the method is called once when the class is initialized, and never a

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 12:18

    If you have an Objective-C class, it's easiest to just override +initialize. However, make sure subclasses of your class also override +initialize or else your class's +initialize may get called more than once! If you want, you can use dispatch_once() (mentioned below) to safeguard against multiple calls.

    class MyView : UIView {
      override class func initialize () {
        // Do stuff
      }
    }
    

     

    If you have a Swift class, the best you can get is dispatch_once() inside the init() statement.

    private var once = dispatch_once_t()
    
    class MyObject {
      init () {
        dispatch_once(&once) {
          // Do stuff
        }
      }
    }
    

    This solution differs from +initialize (which is called the first time an Objective-C class is messaged) and thus isn't a true answer to the question. But it works good enough, IMO.

提交回复
热议问题