访问属性方法和类字段之间的区别(Objective-C) [英] Difference between accessing property methods and class fields (Objective-C)
问题描述
假设我有这段代码:
@interface Foo : NSObject {
Bar *bar;
}
@property (retain, nonatomic) Bar *bar;
@end
使用这个字段/属性时,行之间有什么区别:
When using this field/property, is there any difference between lines:
[self.bar doStuff];
和
[bar doStuff];
?
在赋值时,property 方法会执行正确的保留,但是如上所述对属性的读取访问呢?有什么区别吗?
When doing assignment, property method will perform correct retaining, but what about the read access to the property, as described above? Is there any difference?
推荐答案
有很大的不同.[self.bar doStuff]
等价于 [[self bar] doStuff]
There is a big difference.
[self.bar doStuff]
is equivalent to [[self bar] doStuff]
[bar doStuff]
等价于 [self->bar doStuff]
前者使用accessor方法,后者只是直接访问实例变量bar.
The former uses the accessor method, the latter just accesses the instance variable bar directly.
如果您在 bar
属性上使用 @synthesize
指令,编译器将为您生成两个方法:
If you use the @synthesize
directive on your bar
property, the compiler will generate two methods for you:
- (void)setBar:(Bar*)b;
- (Bar*)bar;
另请注意,编译器生成的 setter 方法会保留您在 @property
声明中告诉它的 Bar
实例.
Also note, that the compiler generated setter method is retaining your Bar
instance as you told it in the @property
declaration.
这篇关于访问属性方法和类字段之间的区别(Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!