【问题标题】:dispatch_async Nested Blockdispatch_async 嵌套块
【发布时间】:2023-04-02 04:22:01
【问题描述】:

我正在使用 dispatch_async 方法在主队列中执行任务。但它会导致保留周期:

下面是sn-p的代码:

self.test = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", self);
        });
   };

我无法正确理解它创建保留周期的原因。因为我的控制器没有 dispatch_async 块的所有权。

【问题讨论】:

  • Property test 保留闭包,并且闭包包含对 self 的引用,该引用本身在块中并不重要

标签: ios objective-c xcode grand-central-dispatch objective-c-blocks


【解决方案1】:

尝试使用weakSelf

__weak typeof(self) weakSelf = self;

self.test = ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%@", weakSelf);
    });
};

【讨论】:

  • 但是self 可能会在外部块的运行和内部块的(异步)运行之间被释放,这可能不是他想要的
【解决方案2】:

如果您不希望外部块保留self,但希望内部块能够在调度后保持self 处于活动状态,可能是这样的:

typeof(self) __weak weakSelf = self;
self.test = ^{
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", strongSelf);
        });
    }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    相关资源
    最近更新 更多