Maksym Bilan
1 min readApr 24, 2015

iOS Objective C project: NSClassFromString method for Swift classes

If you use Swift classes in the Objective C project, you may be faced with the problem, that NSClassFromString method always returns nil. You need to call NSClassFromString from Swift code first of all, and don’t forget about format:

#appName.#className

But if you have many targets in your project or the name of the project is different than the name of the target you need to use the following format:

#appName_#targetName.#className

As a solution, I provide the following extension for NSObject:

extension NSObject {
class func swiftClassFromString(className: String) -> AnyClass! {
if var appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey(“CFBundleName”) as! String? {
let fAppName = appName!.stringByReplacingOccurrencesOfString(“ “, withString: “_”, options: NSStringCompareOptions.LiteralSearch, range: nil)
return NSClassFromString(“\(fAppName).\(className)”)
}
return nil;
}
}
Maksym Bilan
Maksym Bilan

Written by Maksym Bilan

Software Engineer at @MySwimPro |  swift/objc/c++ | 🇺🇦 | family 👨‍👩‍👧 | swimmer 🏊‍♂️ | optimist ⚡️ | superhero for my 👧

Responses (1)