Reputation: 10585
I have a few questions about properties declared in protocols.
Return type variance
@protocol IHaveProperties
@required
@property (nonatomic, strong) IAmOfTypeX *propertyOfProtocolType;
@property (nonatomic, strong) NSArray *array;
@end
@interface ClassThatHasProperties : NSObject<IHaveProperties>
@property (nonatomic, strong) ImplementationOfTypeX *propertyOfProtocolType;
@property (nonatomic, strong) NSMutableArray *array;
@end
Okay, so I tried this with a protocol/class combination and to my chagrin, it compiled.
How does that work? Wouldn't this technically not conform to the interface?
Property declaration modifiers
@protocol IHaveProperty
@required
@property (nonatomic, strong, readonly) *example;
@end
@interface HaveProperty : NSObject<IHaveProperty>
@property (nonatomic, strong, readonly) *example;
@end
My Mac is restarting right now so I cannot try this out but I would think this would be okay, because the protocol declaration has nothing backing it. All the modifiers wouldn't be of interest to a caller, only to the class implementing the protocol.
Upvotes: 1
Views: 196
Reputation: 485
If you look at the <NSObject>
Protocol, you can see that it holds methods and properties together:
@protocol NSObject
- (BOOL)isEqual:(id)object; @property (readonly) NSUInteger hash;
@property (readonly) Class superclass;
- (Class)class OBJC_SWIFT_UNAVAILABLE("use 'anObject.dynamicType' instead");
- (instancetype)self;
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
- (BOOL)isProxy;
- (BOOL)isKindOfClass:(Class)aClass;
- (BOOL)isMemberOfClass:(Class)aClass;
- (BOOL)conformsToProtocol:(Protocol *)aProtocol;
- (BOOL)respondsToSelector:(SEL)aSelector;
- (instancetype)retain OBJC_ARC_UNAVAILABLE;
- (oneway void)release OBJC_ARC_UNAVAILABLE;
- (instancetype)autorelease OBJC_ARC_UNAVAILABLE;
- (NSUInteger)retainCount OBJC_ARC_UNAVAILABLE;
- (struct _NSZone *)zone OBJC_ARC_UNAVAILABLE;
@property (readonly, copy) NSString *description; @optional @property
(readonly, copy) NSString *debugDescription;
@end
You must have used description
or superclass
properties. There's no difference in how a property is treated, as compared to a function. The class implementing the protocol would be providing the getter and / or setter of the property of a protocol. And similarly the class which owns the delegate object would call its properties like: self.delegate.propertyName.
Upvotes: 0