NSClassFromString() 总是返回 nil [英] NSClassFromString() always returns nil

查看:24
本文介绍了NSClassFromString() 总是返回 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码打印 nil,尽管 ListCell 是一个有效的类.

The following code prints nil, despite ListCell is a valid class.

var lCellClass : AnyClass! = NSClassFromString("ListCell");

println(lCellClass);

文档说方法返回

aClassName 命名的类对象,如果当前没有加载该名称的类,则为 nil.如果 aClassNamenil,则返回 nil.

The class object named by aClassName, or nil if no class by that name is currently loaded. If aClassName is nil, returns nil.

我还尝试获取当前已加载的视图控制器的 NSClassFromString(),但仍然获取 nil

I also tried to get NSClassFromString() of current viewcontroller which is LOADED but still get nil

可能是什么问题?

更新:即使尝试这样做 NSClassFromString("Array") 我仍然得到 nil

Update: Even trying to do this NSClassFromString("Array") I still get nil

推荐答案

NSClassFromString 函数确实适用于(纯和 Objective-C 派生的)swift 类,但是仅当您使用完全限定名称时.

The NSClassFromString function does work for (pure and Objective-C-derived) swift classes, but only if you use the fully qualified name.

例如,在名为 MyApp 的模块中,有一个名为 Person 的纯 swift 类:

For example, in a module called MyApp with a pure swift class called Person:

let personClass: AnyClass? = NSClassFromString("MyApp.Person")

模块名称由产品模块名称"(PRODUCT_MODULE_NAME) 构建设置定义,通常与您的目标名称相同(应用了一些规范化,例如删除空格).

The module name is defined by the "Product Module Name" (PRODUCT_MODULE_NAME) build setting, typically the same name as your target (with some normalization applied to e.g. remove spaces).

这是非典型的,但是如果您正在加载的类在当前模块中并且您在编译时不知道模块名称,例如因为代码是作为多个目标的一部分编译的,所以可以动态查找bundle名称,通常对应模块名称:

This is atypical, but if the class you're loading is in the current module and you don't know the module name at compile-time e.g. because the code is compiled as part of multiple targets, you can look up the bundle name dynamically, which usually corresponds to the module name:

let moduleName = Bundle.main.infoDictionary!["CFBundleName"] as! String
let personClass: AnyClass? = NSClassFromString(moduleName + "." + "Person")

我不建议这样做,除非你在编译时真的不知道.

I don't recommend this however unless you really don't know at compile-time.

参见将 Swift 与 Cocoa 和 Objective-C 结合使用 了解更多信息.

See Using Swift Class Names with Objective-C APIs in Using Swift With Cocoa and Objective-C for more information.

这篇关于NSClassFromString() 总是返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆