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;
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Maksym Bilan
Maksym Bilan

Written by Maksym Bilan

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

Responses (1)

Write a response

Excelente, solo me faltaba reemplazar el espacio en blanco por _ !!!! Mil gracias :)