Objective-C: Does Category, which implements a protocol, add an existing class, makes objects conform to this protocol?

Objective-C: Does Category, which implements the protocol, add an existing class so that all objects created from this class conform to this protocol?

More specific:

[myObject conformsToProtocol:@protocol(ProtocolThatWasImplementedViaACategory)];

returns TRUE?

+4
source share
1 answer

Yes, that’s true - provided that you add the correct ad to the @interface ad of your category. You can check it 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

Conclusion:

matches dummy? 1

You can read an explanation of how the documentationconformsToProtocol: works :

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>
+1

Source: https://habr.com/ru/post/1538689/


All Articles