关于C#:为什么不在init和dealloc方法中使用访问器方法?

Why not use accessor methods in init and dealloc method?

本问题已经有最佳答案,请猛点这里访问。

在线程"我如何管理内存"中,作者说"我不会在init和dealloc中使用完整形式,因为它可能会触发KVO或产生其他副作用。"
我不明白你的意思?

来源http://inessential.com/2010/06/28/how_i_manage_memory


我认为作者应该更加注意命名约定。

1
@property (nonatomic, retain) NSString *something;

应该合成

1
@synthesize something = _something;

这样您可以引用self.something来使用访问器方法或_something来使用支持该属性的ivar。它不容易出错。

关于你的问题。当您拥有一个访问者时,除了在该访问器方法中设置该属性(如通知另一个对象或更新UI)之外,您可能正在做其他事情。你可能不希望在init或dealloc上这样做。这就是为什么你可能想要直接访问ivar,但情况并非总是如此。


他指的是通过自我符号访问您的@properties。合成属性时,会自动为您创建该变量的getter和setter:

1
2
3
4
5
6
7
8
9
10
11
12
13
@property (nonatomic,strong) MyClass myVar;

@synthesize myVar = _myVar;

- (MyVar *)myVar
{
   return _myVar;
}

- (void)setMyVar:(MyClass *)myVar
{
  _myVar = myVar;
}

这些方法是在定义和/或合成属性时为幕后创建的(取决于Xcode版本)

所以当你这样做

1
self.myVar = 5;

你实际上在做[self setMyVar:5];

但是,可以使用以下表示法直接访问变量并绕过setter

1
_myVar = 5;

例:

1
2
3
4
5
6
7
8
9
10
11
12
@property (nonatomic,strong) MyClass myVar;

@synthesize myVar = _myVar;


 - (void)someMethod
{
    // All do the same thing
    self.myVar = 5;
    [self setMyVar:5];
    _myVar = 5;
}

本文作者建议您不要在dealloc和init方法中使用getter和setter,而是使用_myVar表示法直接访问变量。

有关最佳实践等的更多信息,请参阅此答案,但这是一个值得商榷的问题:为什么我不能在init / dealloc中使用Objective C 2.0访问器?