【问题标题】:dispatch_async and retain (non-ARC)dispatch_async 和保留(非 ARC)
【发布时间】:2016-10-29 22:49:38
【问题描述】:

在非 ARC 应用程序中,我有一个 NSOperation 子类,它由委托排队,如下所示:

// note that the delegate and element properties are retained

-(id)initWithDelegate:(id<SomeDelegate>)inDelegate element:(SomeElement *)inElement
{
    if (self = [super init])
    {
        [self setDelegate:inDelegate];
        [self setElement:inElement];
    }
}

-(void)dealloc
{
    [_delegate release];
    [_element release];
    [super dealloc];
}

-(void)main
{
    // do stuff

    dispatch_async(dispatch_get_main_queue(), ^{
         [[self delegate] doSomething:[self element]];
    });
}

由于 [[self delegate] doSomething:[self element]] 将在我的 NSOperation 对象可能已被释放后被调用,因此在将此操作添加到队列之前,我是否需要确保在委托中保留“元素”?元素对象保留在应用程序的其他地方,但它可能会在那里释放。我需要确保当我的委托从 NSOperation 收到它时,它仍然是一个有效的对象。

只是想知道在 dispatch_async 中调用它的行为是否会保留传递给它的参数。我当然可以使用 NSInvocation 和 performSelectorOnMainThread 来保留它。

【问题讨论】:

  • 抱歉 - 正在从初始化返回 self。我没有将它添加到我的问题中,但它在原始代码中。
  • Josh 是正确的(见下文)。请参阅块编程主题:块和变量中的Objective-C Blocks

标签: objective-c nsoperation retain dispatch-async


【解决方案1】:

队列将在入队时保留 Block,而 Block 将保留它捕获的对象,例如 self。由于此处的self 对其element 有很强的引用,因此element 将至少在Block 运行之前有效。

请注意,对象具有对其委托的强引用是不寻常的:确保那里没有完整的保留循环。

【讨论】:

    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2011-12-09
    相关资源
    最近更新 更多