NSClassFromString() always returns nil

▼魔方 西西 提交于 2019-11-29 01:26:57

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

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

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

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).

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.

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

It's also possible to specify a name for the symbol in Objective-C which omits the namespace in objective C by using the @objc annotation. If you prefer to use the name without the module, just use the same class name:

@objc(Foobar)
class Foobar{

}

NSClassFromString("Foobar") will return the class Foobar.

This may be problem that your class have not extend from NSObject. As by default swift does not have superclass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!