Defining categories for protocols in Objective-C?

后端 未结 7 903
走了就别回头了
走了就别回头了 2020-12-02 10:39

In Objective-C, I can add methods to existing classes with a category, e.g.

@interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
@end
         


        
7条回答
  •  一整个雨季
    2020-12-02 11:05

    It isn't really meaningful to do so since a protocol can't actually implement the method. A protocol is a way of declaring that you support some methods. Adding a method to this list outside the protocol means that all "conforming" classes accidentally declare the new method even though they don't implement it. If some class implemented the NSObject protocol but did not descend from NSObject, and then you added a method to the protocol, that would break the class's conformance.

    You can, however, create a new protocol that includes the old one with a declaration like @protocol SpecialObject .

提交回复
热议问题