"初始化" Swift中类的类方法? [英] "initialize" class method for classes in Swift?

查看:88
本文介绍了"初始化" Swift中类的类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类似于Objective-C的 +(void)initialize 类方法的行为,因为该方法在初始化类时被调用一次,而且从不此后再次。

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 again thereafter.

类中的简单类init(){} 关闭会非常时尚!显然,当我们在结构闭包中使用 class var s而不是 static var s时,这一切都很好!

A simple class init () {} in a class closure would be really sleek! And obviously when we get to use "class vars" instead of "static vars in a struct closure", this will all match really well!

推荐答案

如果你有一个Objective-C类,最简单的就是覆盖 +初始化。但是,请确保您班级的子类还覆盖 + initialize ,否则您的班级 + initialize 可能不止一次被召唤!如果需要,您可以使用 dispatch_once()(如下所述)来防止多次通话。

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
  }
}

 

如果你有Swift课程,你可以获得的最好成绩是 dispatch_once() init()语句中。

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
    }
  }
}

这个解决方案不同于 + initialize (这是第一次对Objective-C类进行消息调用),因此不是问题的真正答案。但它足够好,IMO。

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.

这篇关于"初始化" Swift中类的类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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