2017-04-11 31 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() 
}