2017-04-11 6 views
1

Swift 3.1 deprecates initialize(). How can I achieve the same thing?と同じ問題に遭遇しました@ジョーダンスミスのソリューションは非常に印象的です、私は実装に興味があったが、実際にいくつかのトラブルに会った、ここでいくつかのキーコードは、コメントを参照してくださいなぜログ機能UIViewController呼び出されていない、プロトコルに準拠しています。 UIViewControllerがキャッチしかしT == UIViewController.selffalseあるた理由:迅速なタイプ判定について混乱していますか?

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 -protocolに@objcというキーワードを付ける必要があります。

@objc protocol Conscious { 
    static func awake() 
} 

次に、class_conformsToProtocol -functionを使用する必要があります。

let type = types[index]! 
if class_conformsToProtocol(type, Conscious.self) { 
    let item = type as! Conscious.Type 
    item.awake() 
} 
関連する問題