2017-04-11 54 views
1

遇到了同样的问题与Swift 3.1 deprecates initialize(). How can I achieve the same thing?,@Jordan史密斯的解决方案是非常令人印象深刻,当时我感兴趣的实现,但遇到了在实践中一些麻烦,下面是一些关键的代码,看到的评论,为什么在UIViewController日志功能没有被调用,它符合协议;为什么UIViewController被抓住了,但T == UIViewController.selffalse在swift中对类型判断感到困惑?

protocol Conscious { 
    static func awake() 
} 

/** extension */ 
extension UIViewController: Conscious { 
    static func awake() { 
     if self == UIViewController.self { 
      print(self, #function)  // never came here, but seems should come 
     } 
    } 
} 

/** main */ 
private static let _operation: Void = { 
    let typeCount = Int(objc_getClassList(nil, 0)) 
    let types = UnsafeMutablePointer<AnyClass?>.allocate(capacity: typeCount) 
    let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass?>(types) 
    objc_getClassList(autoreleasingTypes, Int32(typeCount)) 

    for index in 0 ..< typeCount { 
     (types[index] as? Conscious.Type)?.awake() 

     let T = types[index]! 
     let vc = UIViewController() 
     print(T, vc.isKind(of: T), T == UIViewController.self) 
     /* 
      Strange things: 
      UIResponder true false 
      UIViewController true false(why is false) 
      UISearchController false false 
     */ 
    } 

    types.deallocate(capacity: typeCount) 
}() 
+0

你有什么问题吗? – rmaddy

+0

@rmaddy对不起, – quentinjin

+0

OK,所以再次看到在代码的注释,你有什么问题吗? – rmaddy

回答

0

嗯,它看起来像UIViewController的迅速扩展不使用objc方法可见。 所以这里是我的解决方案,基于this topic

首先,你需要标记Conscious - 方案与@objc关键字。

@objc protocol Conscious { 
    static func awake() 
} 

然后你需要使用class_conformsToProtocol功能。

let type = types[index]! 
if class_conformsToProtocol(type, Conscious.self) { 
    let item = type as! Conscious.Type 
    item.awake() 
}