何时使用self.propertyname和_propertyname

时间:2012-12-17 03:36:25

标签: objective-c properties

  

可能重复:
  How does an underscore in front of a variable in a cocoa objective-c class work?
  Difference between self.ivar and ivar?
  Synthesized property and variable with underscore prefix: what does this mean?

要在对象c中使用属性,我有两个选择,我应该使用哪一个?

choice1:self.property = xxxx;

choice2:_property = xxx

例如:

//.h file

@interface ViewController : UIViewController

    @property (retain, nonatomic) NSArray *myArray;

@end

//.m file

@interfaceViewController ()

@end

@implementation ViewController

- (void)doing {

    _myArray = [[NSArray alloc] init]; //choice one
    self.myArray = [[NSArray alloc] init]; //choice two
}
@end

2 个答案:

答案 0 :(得分:2)

你正在做两件完全不同的事情。

_myVar = [[NSArray alloc] init];

在上面的代码中,您可以直接访问变量。

self.myVar = [[NSArray alloc] init];

在上面的代码中,您调用的是setter方法,它等同于

[self setMyVar:[[NSArray alloc] init]];

通常,setter(连同getter)提供内存管理和同步功能,因此更可取,并且通常使用它更安全,而不是直接访问ivar。

下划线语法仅仅是一种不混淆ivar和属性的惯例,因为一个典型的错误是误解了它并意外地使用myVar而不是self.myVar。使用下划线语法是为了阻止这种不良做法。

答案 1 :(得分:0)

我知道这个问题很频繁,但无论如何我都会回答。

下划线语法访问支持该属性的实例变量,而点语法只是附件方法的包装器:

object.property == [object property]
object.property = x == [object setProperty:x]

因此,您应尽可能使用点语法或附件方法,以确保一切都得到妥善处理。例如,非ARC应用程序中的垃圾收集。您必须使用实例变量来执行初始化,取消分配或自定义附件方法,但这些都是特殊情况。要获得详细的概述,请阅读Objective-C手册中有关属性的章节:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW1