在readonly属性之后进一步澄清_property?

时间:2014-01-07 21:05:51

标签: objective-c properties readonly ivars

在接口部分设置readonly属性时,“禁用”属性的setter方法。我需要澄清一下:

  1. 如果我们可以使用_propertyName设置它,那么readonly属性的重点是什么?
  2. 如果我们的属性是readwrite,何时使用_propertyName?

  3. 此外,我理解我们使用setter方法进行抽象,而不是仅使用_propertyName分配值。还有其他原因不使用_propertyName吗?

  4. 以下是一些示例代码。三江源。

    接口部分

    @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;
    }
    

1 个答案:

答案 0 :(得分:2)

  1. 重点是"封装"。没有其他文件可以直接设置属性。该属性只能从给定文件中设置,例如,使用init或使用专门方法。

  2. 大多数人会告诉您,您应该仅在_property方法,init(如果您不使用ARC)中直接使用dealloc,当然,如果您是实现自己的setter和getter。即使该属性声明为readonly,通常也会在类扩展中声明它为readwrite。因此,对于其他文件,它将保留readonly,但对于声明它的实现文件(类),它将为readwrite

  3. 很多原因,例如"继承" - 可以覆盖setter。对于copy属性,复制由setter处理。使用MRC(不是ARC),setter甚至更重要(它们处理保留和释放)。

相关问题