swift2.0 NSClassFromString的使用 20151112-Xcode7

本文介绍如何在iOS项目中,通过给定的controller名称,从tableView的cell中自动创建并跳转到相应的UIViewController。使用Swift语言结合Objective-C API实现此功能,并详细解释Swift类名在Objective-C环境中的命名空间规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做项目过程中,由于有很多页面,在一个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")

转载于:https://www.cnblogs.com/qqsscc/p/4958574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值