Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Thursday, December 12, 2013

iOS Check if an Object Belongs to a Class

So, you want to tell if an NSObject inherits from a certain type of class, right?

Sometimes when dealing with abstract APIs, or after a night of exceeded the recommended amount of beer while coding, we find ourselves in the morning, headaches and all, dealing with collections of objects for which we'd really like to know their class type. Puritans of yesteryear perhaps would scoff at your untidy and drunken implementation, and cast askew glances at your choice of languages and their non-strongly-typed-collections, but you won't find any judging eyes here, no sir. 

Here's a couple of aspirin, and some short winded code that will help you check the class-type of any object that passes through your fingers:

  NSObject *obj = [NSObject alloc];
  if([obj isMemberOfClass:[NSObject class]]){
    NSLog(@"Its an Object!");
  } else{
    NSLog(@"Its NOT an Object! ... wait, how is that possible?");


>> Its an Object!

So, this little bit of code above, that's good for knowing if the class type IS EXACTLY a NSObject class... but what if we just generally want to know if it has NSObject somewhere in its lineage? Well then, we need to whip out this dandy little method instead of the one above:

  NSObject *iAmAString = [NSString stringWithString:@"Who am I really?"];
  if([iAmAString isKindOfClass:[NSObject class]]){
    NSLog(@"Its an Object!");
  } else{
    NSLog(@"Its NOT an Object! ... impossibru!");

>> Its an Object!

There you go, the ability to tell if a class IS A type of a certain class, and whether a class HAPPENS TO INHERIT FROM that class.

Go forth and drunken-code no more, but if you still need this post, give it a +1 and it will always be at the top of your searches. Good luck!

About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates:

Popular Posts

Designed By Seo Blogger Templates