手动保留ARC

时间:2011-10-17 10:46:07

标签: objective-c ios memory-management ios5 automatic-ref-counting

在ARC之前我有以下代码在异步操作正在进行时保留委托:

- (void)startAsyncWork
{
    [_delegate retain];
    // calls executeAsyncWork asynchronously
}

- (void)executeAsyncWork
{
    // when finished, calls stopAsyncWork
}

- (void)stopAsyncWork
{
    [_delegate release];
}

与ARC的这种模式相同的是什么?

3 个答案:

答案 0 :(得分:31)

我偶尔需要手动保留和释放内容(有时仅用于调试)并提出以下宏:

#define AntiARCRetain(...) void *retainedThing = (__bridge_retained void *)__VA_ARGS__; retainedThing = retainedThing
#define AntiARCRelease(...) void *retainedThing = (__bridge void *) __VA_ARGS__; id unretainedThing = (__bridge_transfer id)retainedThing; unretainedThing = nil

这可以通过使用__bridge_retained和__bridge_transfer来转换东西(void *)来导致事物被保留,或者在不调用retain的情况下创建强引用。

玩得开心,但要小心!

答案 1 :(得分:10)

为什么不在异步任务期间将您的委托对象分配给强大的ivar?

或者在executeAsyncWork

中有一个局部变量
- (void)executeAsyncWork
{
    id localCopy = _delegate;

    if (localCopy != nil) // since this method is async, the delegate might have gone
    {
        // do work on local copy
    }
}

答案 2 :(得分:3)

这样的事情:

- (void)startAsyncWork
{
    id<YourProtocol> delegate = _delegate;
    dispatch_async(/* some queue */, ^{
        // do work
        [delegate doSomething];
    }
}

只要需要,该块将保留代表......