当在一个客观的c子类中引用它时,ivar的下划线丢失了?

时间:2014-05-01 04:59:02

标签: objective-c

以下是代码:

Rectangle.h

#import <Foundation/Foundation.h>

@interface Rectangle : NSObject

@property int width;
@property int height;

- (int)area;
- (int)perimeter;
- (void)setWidth:(int)w andHeight:(int)h;

@end

Rectangle.m

#import "Rectangle.h"

@implementation Rectangle

- (int)area
{
    return _width * _height;
}

- (int)perimeter
{
    return (_width + _height) * 2;
}
- (void)setWidth:(int)w andHeight:(int)h
{
    _width = w;
    _height = h;
}

@end

Square.h

#import "Rectangle.h"

@interface Square : Rectangle

- (void)setSide:(int)a;
- (int)side;

@end

Square.m

#import "Square.h"

@implementation Square

- (void)setSide:(int)s
{
    [self setWidth:s andHeight:s];
}

- (int)side
{
    return self._width;
}

@end

问题出现在- (int)side的{​​{1}}方法中。除非我将Square.m更改为self._width,否则它无效。这是为什么呢?当我在self.width中创建该属性时,我没有在Rectangle.h中对其进行综合,因此自动创建了Rectangle.m ivar。由于该属性是在_width中声明的,因此.h是否公开?或者它不公开,我实际看到的是属性宽度的隐藏吸气剂?所以它真的在做:

ivar

点符号让我感到困惑的是它是指- (int)side { return [self width]; } 还是属性本身的getter方法。有人可以澄清没有任何宽度ivar吗?

1 个答案:

答案 0 :(得分:3)

  

点符号让我感到困惑,如果它指的是ivar,   或者属性本身的getter方法。有人可以澄清这一点   伊瓦尔没有宽度?

点符号指的是属性访问器,在这种情况下为width。也就是说,

int foo = someSquare.width;

与:

完全相同
int foo = [someSquare width];

因此,尝试将点符号与前导下划线self._width一起使用,是没有意义的,因为没有名为_width的属性。有一个名为_width的实例变量,但您不能使用点表示法访问它。

  

由于该物业是在.h中宣布的,因此不是公共场所吗?

是的,ivar可公开访问,您可以使用指针表示法来访问它:

int foo = self->_width;

但不要这样做。改为使用属性访问器。