Dan*_* S. 16 inheritance properties objective-c
摘要:
这个问题是关于属性的继承以及从继承该属性的类的内部和外部的不同读/写访问.
细节:
我有一个类A和另一个B继承自的类A.有someProperty宣布的财产A.我希望该属性只能从这些类外部读取,并从内部读/写.
只有一个类,这很简单:在.hreadonly中声明属性,然后在类别的.m内再次声明为readwrite.完成.
但是有两个类,一个派生自另一个,我得到以下编译器警告B:
自动属性合成不会合成属性'someProperty',因为它是'readwrite'但它将通过另一个属性合成'readonly'
这是代码:
啊:
#import <Foundation/Foundation.h>
@interface A : NSObject
// This property shall be readonly from outside, but read/write from subclasses
@property (readonly) SInt32 someProperty;
@end
Run Code Online (Sandbox Code Playgroud)
上午:
#import "A.h"
@implementation A
@end
Run Code Online (Sandbox Code Playgroud)
BH:
#import <Foundation/Foundation.h>
#import "A.h"
@interface B : A
@end
Run Code Online (Sandbox Code Playgroud)
BM:
#import "B.h"
@interface B ()
// compiler warning in the following property declaration:
// /Users/.../B.m:12:41: Auto property synthesis will not synthesize property
// 'someProperty' because it is 'readwrite' but it will be synthesized
// 'readonly' via another property
@property (readwrite) SInt32 someProperty;
@end
@implementation B
@end
Run Code Online (Sandbox Code Playgroud)
为什么会出现此警告,我应该如何构建代码以避免它?
Wai*_*ain 10
您需要在拥有的类(A)上将该属性声明为读写,然后在子类(B)上重新声明,以使编译器意识到您要在那里使用它.因此,A托管访问器方法并B使用它.通常,您不希望B创建另一个访问器方法,因此您可以使用@dynamic告诉编译器超类(技术上,只是另一个类)将提供实现.
请注意,你也可以A在B.m中声明一个类别(不是扩展名),它明确地声明了访问器方法(不使用属性,只是一个方法),因为那是你真正感兴趣的东西(你实际上并不想要)属性指定的任何其他东西,你真的不想要确保属性属性在超类和子类中匹配的维护开销)...