我对协议中声明的属性有几个问题。
返回类型差异
@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
好的,所以我尝试了一个协议/类组合,并且我感到懊恼,它编译了。
这是如何工作的?这技术上不符合界面吗?
属性声明修饰符
@protocol IHaveProperty
@required
@property (nonatomic, strong, readonly) *example;
@end
@interface HaveProperty : NSObject<IHaveProperty>
@property (nonatomic, strong, readonly) *example;
@end
我的Mac现在正在重新启动,所以我不能尝试这个,但我会认为这没关系,因为协议声明没有任何支持它。调用者不会对所有修饰符感兴趣,只对实现该协议的类感兴趣。
答案 0 :(得分:0)
如果查看<NSObject>
协议,您可以看到它将方法和属性结合在一起:
@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
您必须使用description
或superclass
属性。与函数相比,属性的处理方式没有区别。实现该协议的类将提供协议属性的getter和/或setter。类似地,拥有委托对象的类将调用其属性,如:self.delegate.propertyName.