Question

I have the following method. I currently use try/catch blocks to determine whether the argument is a class or a protocol, and it seems like it's causing a memory leak. What's the correct way to determine whether x is a class or a protocol?

[self _injectMacro:[MyClass class]];
[self _injectMacro:@protocol(MyProtocol)];

+ (id)_injectMacro:(id)x
{
    @try {
        return NSStringFromProtocol(x);
    }
    @catch (NSException *exception) {

    }

    @try {
        return NSStringFromClass(x);
    }
    @catch (NSException *exception) {

    }

    return nil;
}
Was it helpful?

Solution

You can use isKindOfClass to find whether or not an id is a protocol:

id x = [NSObject class];
id y = @protocol(NSObject); 
NSLog(@"%d", [x isKindOfClass:[Protocol class]]); // 0
NSLog(@"%d", [y isKindOfClass:[Protocol class]]); // 1

You have to import the ObjectiveC.Protocol module to use Protocol:

@import ObjectiveC.Protocol;

Or if you are not using modules, just import the Protocol header:

#import <objc/Protocol.h>

To check if an id is a class or an instance have a look a this answer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top