How to handle Objective-C protocols that contain properties?

后端 未结 6 1871
醉梦人生
醉梦人生 2020-12-07 07:56

I\'ve seen usage of Objective-C protocols get used in a fashion such as the following:

@protocol MyProtocol 

@required

@property (readonly)         


        
6条回答
  •  执念已碎
    2020-12-07 08:14

    Take a look at my article PROPERTY IN PROTOCOL

    Suppose I have MyProtocol that declares a name property, and MyClass that conforms to this protocol

    Things worth noted

    1. The identifier property in MyClass declares and generates getter, setter and backing _identifier variable
    2. The name property only declares that MyClass has a getter, setter in the header. It does not generate getter, setter implementation and backing variable.
    3. I can’t redeclare this name property, as it already declared by the protocol. Do this will yell an error

      @interface MyClass () // Class extension
      
      @property (nonatomic, strong) NSString *name;
      
      @end
      

    How to use property in protocol

    So to use MyClass with that name property, we have to do either

    1. Declare the property again (AppDelegate.h does this way)

      @interface MyClass : NSObject 
      
      @property (nonatomic, strong) NSString *name;
      
      @property (nonatomic, strong) NSString *identifier;
      
      @end
      
    2. Synthesize ourself

      @implementation MyClass
      
      @synthesize name;
      
      @end
      

提交回复
热议问题