【问题标题】:How do I refer to the class type to call constructor or other class functions inside the same class?如何引用类类型来调用同一个类中的构造函数或其他类函数?
【发布时间】:2015-06-07 05:16:55
【问题描述】:

我有这个代码,我需要复制并粘贴到许多类(我知道...),我正在尝试找到一种方法来不为每个新类编辑类名。如果我可以重构代码而无需过多考虑重命名类 func 和对初始化程序的调用,我也更愿意。有什么办法吗?

@objc class MyClass : NSObject, NSCopying {
    init() {}

    func copyWithZone(zone: NSZone) -> AnyObject {
       return MyClass()
    }

   class func myFunction() {}

   func myMethod() {
       MyClass.myFunction()
   }
}

编辑:

这些类是NSObject 的子类,因此在这种情况下使用泛型将不起作用。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您可以将他们的超类设为MyClass,而不是将您的班级的超类设为MyClass,您可以这样定义:

    @objc class MyClass : NSObject, NSCopying {
        required override init() {
            super.init()
        }
    
        func copyWithZone(zone: NSZone) -> AnyObject {
            return self.dynamicType()
        }
    
        class func myFunction() {
            // ...
        }
    
        func myMethod() {
            self.dynamicType.myFunction()
        }
    }
    

    dynamicType 指的是实例的类。对于MyClass 的实例,dynamicTypeMyClass。对于MyClass 的子类,dynamicType 将引用该子类。

    有关required 初始化程序和dynamicType 的说明,请查看Implementing NSCopying in Swift with subclasses

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 2011-02-15
      • 2012-05-12
      • 2023-04-03
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      相关资源
      最近更新 更多