_property和self.property之间的区别 [英] Difference between _property and self.property
问题描述
在处理属性时,我对于正确的约定感到有些困惑。我将通过一个例子说明我的问题。所以从下面的例子我知道功能上self.loan = self.loan + 250.00;与_loan = _loan + 250.00;相同或者不是吗?我在网上看到很多教程,可能会也可能不会使用这两种方法来访问属性。那么使用_loan和self.loan之间究竟有什么区别(我知道self.loan与[self setLoan:]相同)
I'm slightly confused as to the proper conventions when dealing with properties. I'll illustrate my question through an example. So from the example below I know that functionally "self.loan = self.loan + 250.00;" is the same as "_loan = _loan + 250.00;" or is it not? I see numerous tutorials all over the web that may or may not use both methods to access a property. So what exactly is the difference between using _loan and self.loan (I know that self.loan is the same as [self setLoan:])
//ClassA.h
@interface ClassA: UIViewController
@property double loan;
@end
//ClassA.m
@implementation ClassA
@synthesize loan = _loan;
-(void)doSomething{
self.loan = self.loan + 250.00; //Exhibit A
_loan = _loan + 250.00; // Exhibit B
}
推荐答案
_loan
是一个变量并为其赋值没有特别的副作用。
_loan
is a variable and assigning a value to it has no particular side effect.
self。 loan = self.loan + 250.00
与编写 [self setLoan:[self loan] + 250.00]
基本相同,因为调用方法可以做其他事情而不是简单地设置或获取变量的值。这些方法的额外功能取决于您是否编写它们的自定义版本(setter和getter)或使用 @synthesize
来创建它们,如果使用 @synthesize
,您在 @property
声明中应用了哪些属性。
self.loan = self.loan + 250.00
is essentially the same as writing [self setLoan:[self loan] + 250.00]
in that methods are called that may do other things than simply set or get the value of a variable. The extra things those methods do depend on whether you write custom versions of them (the setters and the getters) or use @synthesize
to create them and, if you use @synthesize
, what attributes you apply in the @property
declaration.
这篇关于_property和self.property之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!