Objective-C: Does adding a Category, that implements a Protocol, to an existing Class, make Objects conform to that Protocol?

StackOverflow https://stackoverflow.com/questions/23382557

  •  12-07-2023
  •  | 
  •  

Question

Objective-C: Does adding a Category, that implements a Protocol, to an existing Class, make all Objects instantiated from that class conform to that Protocol?

More specifically:

[myObject conformsToProtocol:@protocol(ProtocolThatWasImplementedViaACategory)];

returns TRUE?

Was it helpful?

Solution

Yes, it does - assuming that you added a proper declaration in the @interface declaration of your category. You can check it by yourself:

@interface MyClass : NSObject 
@end

@protocol  Dummy <NSObject>

-(void)dummyMethod;

@end

@interface MyClass (MyCategory) <Dummy>

@end

@implementation MyClass (MyCategory) 

+ (void)load {
    BOOL conforms = [self conformsToProtocol:@protocol(Dummy)];
    NSLog(@"conforms to Dummy? %@", @(conforms));
}

@end

The output is:

conforms to Dummy? 1

You can read an explanation on how conformsToProtocol: works in the documentation:

A class is said to “conform to” a protocol if it adopts the protocol or inherits from another class that adopts it. Protocols are adopted by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols:

@interface MyClass : NSObject <AffiliationRequests, Normalization>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top