【问题标题】:when to use self.propertyname and _propertyname [duplicate]何时使用 self.propertyname 和 _propertyname [重复]
【发布时间】:2012-12-04 04:23:44
【问题描述】:

可能重复:
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 中使用属性,我有两种选择,我应该使用哪一种?

选择1:self.property = xxxx;

选择2:_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

【问题讨论】:

  • @CodaFi 请关注骗子链 :)
  • @Jack,这是他的事。 :P
  • 问题不在于下划线语法。他在问两种设置变量的方式之间的区别,这不是语法或约定的问题。
  • 不完全是,这个问题是关于属性的声明,而不是关于 ivar 的访问和使用。
  • 这是有还是没有ARC?

标签: objective-c properties


【解决方案1】:

我知道这个问题很常见,但我还是会回答。

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

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

【讨论】:

    【解决方案2】:

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

    _myVar = [[NSArray alloc] init];
    

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

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

    在上面的代码中你调用了setter方法,相当于

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

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

    下划线语法只是一个约定,不要混淆 ivar 和属性,因为一个典型的错误是错误地使用了 myVar 而不是 self.myVar。使用下划线语法是为了阻止这种不良做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-06
      • 2016-12-21
      • 2021-12-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      相关资源
      最近更新 更多