在接口部分设置readonly属性时,“禁用”属性的setter方法。我需要澄清一下:
如果我们的属性是readwrite,何时使用_propertyName?
此外,我理解我们使用setter方法进行抽象,而不是仅使用_propertyName分配值。还有其他原因不使用_propertyName吗?
以下是一些示例代码。三江源。
接口部分
@property (nonatomic, readonly) NSString *licensePlate;
@property (nonatomic, readonly) NSString *bodyColor;
Implmentation Section
-(id) initWithCarFeatures {
self = [super init]
if (self) {
_licensePlate = @"XSHJDS8687";
_bodyColor = @"blueColor";
}
return self;
}
答案 0 :(得分:2)
重点是"封装"。没有其他文件可以直接设置属性。该属性只能从给定文件中设置,例如,使用init
或使用专门方法。
大多数人会告诉您,您应该仅在_property
方法,init
(如果您不使用ARC)中直接使用dealloc
,当然,如果您是实现自己的setter和getter。即使该属性声明为readonly
,通常也会在类扩展中声明它为readwrite
。因此,对于其他文件,它将保留readonly
,但对于声明它的实现文件(类),它将为readwrite
。
很多原因,例如"继承" - 可以覆盖setter。对于copy
属性,复制由setter处理。使用MRC(不是ARC),setter甚至更重要(它们处理保留和释放)。