swift2.0 NSClassFromString的使用 20151112-Xcode7

最近在做项目过程中,由于有很多页面,在一个tableView中跳转,那么就希望从cell中取出controller Name,自动创建viewcontroller进行跳转

直接上代码:

func viewControllerFromString(name: String) -> UIViewController? {
        let vcName = name
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        // Convert string to class
        let anyobjecType: AnyObject.Type = NSClassFromString(ns + "." + vcName)!
        if anyobjecType is UIViewController.Type {
            // vc is instance
            let vc = (anyobjecType as! UIViewController.Type).init()
            return vc
        }
        return nil
    }

官方说明:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html

Using Swift Class Names with Objective-C APIs

Swift classes are namespaced based on the module they are compiled in, even when used from Objective-C code. Unlike Objective-C, where all classes are part of a global namespace–and must not have the same name–Swift classes can be disambiguated based on the module they reside in. For example, the fully qualified name of a Swift class named DataManager in a framework named MyFramework is MyFramework.DataManager. A Swift app target is a module itself, so the fully qualified name of a Swift class named Observer in an app called MyGreatApp is MyGreatApp.Observer.

In order to preserve namespacing when a Swift class is used in Objective-C code, Swift classes are exposed to the Objective-C runtime with their fully qualified names. Therefore, when you work with APIs that operate on the string representation of a Swift class, you must include the fully qualified name of the class. For example, when you create a document–based Mac app, you provide the name of your NSDocument subclass in your app’s Info.plist file. In Swift, you must use the full name of your document subclass, including the module name derived from the name of your app or framework.

In the example below, the NSClassFromString function is used to retrieve a reference to a class from its string representation. In order to retrieve a Swift class, the fully qualified name, including the name of the app, is used.

let myPersonClass: AnyClass? = NSClassFromString("MyGreatApp.Person")
posted @ 2015-11-12 12:03  qqsscc  阅读(330)  评论(0编辑  收藏  举报