views:

38

answers:

2

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.

+3  A: 

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.

KennyTM
@Kenny,then how would i restrict protocols to only its own methods?
suse
@suse: Could you give an example?
KennyTM
@kenny: I've updated the above question.plz have a look
suse
@suse: That's still the same as what I've said. Protocol B adopting protocol A isn't the crux. Even if you call `[objA blahBlahBlah];` it will still be a warning because `-blahBlahBlah` may exist in runtime. If you need error, use `-Werror`.
KennyTM
A: 

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.

mouviciel