How to restrict the class to access the methods of specified protocols in Objective-C?
When i'm trying to call protocolA methods, on an object of protocolB, i'm getting compiler warnings", but how would i restrict it to only methods of protocolB, i mean it shouldn't allow me to run the code, it has to give me an error ??? Is there any method to solve this problem in Objective-C?
Example :
// this is protocolA.h
@protocol protocolA
-开发者_开发知识库(void)methodA;
@end
//this is protocolB.h
#import "protocolA"
@protocol protocolB <protocolA>
-(void)methodB;
@end
//this is MyClass.h
#import "protocolA"
@interface MyClass <protocolA>
{}
@end
//this is MyClass.m
@implementation
-(void)applicationDidFinishLaunching
{
id<protocolA> objA = [[MyClass alloc]init];
[objA methodA];//Should work fine
[objA methodB];//**Sholud give me error, but only warning is prompted but able to access methodB using objA and print its contents**
}
-(void)methodA
{
NSLog(@"This is in protocolA");
}
-(void)methodB
{
NSLog(@"This is in protocolB");
}
@end
NOTE:Here i'm extending protocolA in protocolB, but when i create an object of protocolA in MyClass, i should be able to access only the methodA of protocolA not the methodB of protocolB.
Compiler warning is the farthest you can get. You can enable the "treat warnings as errors" flag (-Werror
).
The reason it's just a warning is because one can modify the class at runtime. That means anyone can insert or remove or change a method of any class. Then a previously non-existent call may suddenly become valid. The compiler cannot check if the code's deliberately abusing this runtime feature, so a warning is the best bet. Not to mention it's just an artificial restriction by protocol.
The line:
id<protocolA> objA;
tells that objA
conforms to <protocolA>
. It doesn't tell whether objA
conforms to <protocolB>
or not.
Thus the compiler doesn't know if it is an error to send methodB
message to objA
. Indeed in this case, this is not an error.
精彩评论