445

Getting the classname of an object as String using:

object_getClassName(myViewController) 

returns something like this:

_TtC5AppName22CalendarViewController 

I am looking for the pure version: "CalendarViewController". How do I get a cleaned up string of the class name instead?

I found some attempts of questions about this but not an actual answer. Is it not possible at all?

2
  • alternatively … what would an effective parser function for this look like? Commented Jun 30, 2014 at 16:50
  • In case you wish to check if an object is of a certain class see this answer. Commented May 23, 2019 at 10:25

32 Answers 32

1
2
0

I use it in Swift 2.2

guard let currentController = UIApplication.topViewController() else { return } currentController.classForCoder.description().componentsSeparatedByString(".").last! 
Sign up to request clarification or add additional context in comments.

Comments

-1

In my case String(describing: self) returned something like:

< My_project.ExampleViewController: 0x10b2bb2b0>

But I'd like to have something like getSimpleName on Android.

So I've created a little extension:

extension UIViewController { func getSimpleClassName() -> String { let describing = String(describing: self) if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") { let afterDotIndex = describing.index(after: dotIndex) if(afterDotIndex < commaIndex) { return String(describing[afterDotIndex ..< commaIndex]) } } return describing } } 

And now it returns:

ExampleViewController

Extending NSObject instead of UIViewController should also work. Function above is also fail-safe :)

1 Comment

Thats because your passing an instance of the class name instead of a class so in the above example you should pass ExampleViewController.self
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.