Defining categories for protocols in Objective-C?

后端 未结 7 869
走了就别回头了
走了就别回头了 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:17

    extObjC has the NEATEST stuff you can do with Protocols / Categories... first off is @concreteprotocol...

    • Defines a "concrete protocol," which can provide default implementations of methods within protocol.
    • An @protocol block should exist in a header file, and a corresponding @concreteprotocol block in an implementation file.
    • Any object that declares itself to conform to this protocol will receive its method implementations, but only if no method by the same name already exists.

    MyProtocol.h

    @protocol MyProtocol 
    @required - (void)someRequiredMethod;
    @optional - (void)someOptionalMethod;
    @concrete - (BOOL)isConcrete;   
    

    MyProtocol.m

     @concreteprotocol(MyProtocol) - (BOOL)isConcrete { return YES; } ...
    

    so declaring an object MyDumbObject : NSObject will automatically return YES to isConcrete.

    Also, they have pcategoryinterface(PROTOCOL,CATEGORY) which "defines the interface for a category named CATEGORY on a protocol PROTOCOL". Protocol categories contain methods that are automatically applied to any class that declares itself to conform to PROTOCOL." There is an accompanying macro you also have to use in your implementation file. See the docs.

    Last, but NOT least / not directly related to @protocols is synthesizeAssociation(CLASS, PROPERTY), which "synthesizes a property for a class using associated objects. This is primarily useful for adding properties to a class within a category. PROPERTY must have been declared with @property in the interface of the specified class (or a category upon it), and must be of object type."

    So many of the tools in this library open (way-up) the things you can do with ObjC... from multiple inheritance... to well, your imagination is the limit.

提交回复
热议问题