ovatsug25
ovatsug25

Reputation: 8616

How to know if Objective C pointer is of `Class` type?

I would like to know if a pointer in my program is pointing to a Class type.

Something like:

if ([anObject isKindOfClass:[Class class]]])

This an error because [Class class] does not exist.

The closet I can come to is this:

    NSLog(@"Will run");
    const char *nameOfClass = class_getName(@"DoesNotExist");
    if (nameOfClass == NULL || (strlen(nameOfClass) == 0)
    {
        NSLog(@"Not a class");
    } else { 
        NSLog(@"String: %s", nameOfClass);
    }
    NSLog(@"Did run");

Where an empty const char *nameOfClass would tell me that it isn't in fact a Class object. Any other ideas?

Upvotes: 0

Views: 137

Answers (1)

jtbandes
jtbandes

Reputation: 118761

There's an Obj-C runtime function called object_isClass.

#import <objc/runtime.h>
if (object_isClass(anObject))

Another valid approach would be to use class_isMetaClass(object_getClass(anObject)), since the class of a class is a metaclass.

Upvotes: 2

Related Questions