34

这是我以前编写自定义保留设置器的方式:

- (void)setMyObject:(MyObject *)anObject
{
   [_myObject release], _myObject =  nil;
   _myObject = [anObject retain];

   // Other stuff
}

当属性设置为强时,如何使用 ARC 实现这一点。如何确保变量具有强指针?

4

2 回答 2

66

strongivar 级别上照顾自己,所以你只能做

- (void)setMyObject:(MyObject *)anObject
{
   _myObject = anObject;
   // other stuff
}

就是这样。

注意:如果您在没有自动属性的情况下执行此操作,则 ivar 将是

MyObject *_myObject;

然后 ARC 会为您处理保留和释放(谢天谢地)。__strong默认情况下是限定符。

于 2012-04-06T02:00:02.527 回答
5

只是总结一下答案

.h 文件

//If you are doing this without the ivar
@property (nonatomic, strong) MyObject *myObject;

.m 文件

@synthesize myObject = _myObject;

- (void)setMyObject:(MyObject *)anObject
{
    if (_myObject != anObject)
    {
        _myObject = nil;
        _myObject = anObject;
    }
    // other stuff
}
于 2012-12-10T06:00:11.447 回答