0

In Java, C++11 and some other languages you can specify that a method is intended to override another method from a base class or interface, if you then at a later point remove the method from the base class you get a compiler error. I use protocols with optional methods a lot and find that if I remove a method from there I have a tendency to forget to remove the code that implemented the method. This does not generate an error or a warning, thus creating a "dead" method.

Consider:

@protocol Prot <NSObject>
@optional
- (void)bar;
- (void)tempBar;
@end

@interface MyType : NSObject <Prot>
@end

@implementation MyType
- (void)bar { /**/ }
- (void)tempBar { /**/ }
@end

If I at one point remove tempBar from the protocol, I would like to get at least a warning from tempBar being implemented in MyType.

Is there any way in Objective-C to specify that a method is expected to be an implementation of a protocol method?

1 Answers1

1

Objective-C is a dynamic language and this is rather impossible to enforce at compile time. Note that in Obj-C you can actually call methods there are not even there and the app won't crash (well, the default implementation will raise an exception but you can change that behavior).

The method can be also added in an extension, or added at runtime. Or it is just not present in the header.

Note there is also the opposite problem. When subclassing, you can override a method which you don't even know is there, because it is not present in the headers.

This is one of the reasons why Apple is moving to a more predictable language, that is, Swift.

Sulthan
  • 128,090
  • 22
  • 218
  • 270