Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

ios - NSClassFromString() always returns nil

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

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

println(lCellClass);

The docs are saying that method returns

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

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

What can be the problem ?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...