Swift 語法 - Swift通過類名實例化對象


根據類名來實例化對象,比如,要根據一個類名的字符串創建ViewController實例。

let controllerName="SpainAppProto."+xibName  // xibName 形如 XXViewController
var classType: AnyObject.Type=NSClassFromString(controllerName)
var nsobjectype : UIViewController.Type = classType as UIViewController.Type
var viewController: UIViewController = nsobjectype(nibName: xibName, bundle: nil) 

 

但是 在根據 UIViewController.self 來實例化的時候就要稍微轉化下

    var x: String = m.debugDescription  // m為 UIViewController.self
    x = x.stringByReplacingOccurrencesOfString("Optional(", withString: "")
    x = x.stringByReplacingOccurrencesOfString(")", withString: "")
    let anyClass: AnyClass = NSClassFromString(x)
    let viewControllerClass: UIViewController.Type = anyClass as UIViewController.Type
    let viewController = viewControllerClass()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM