gpt4 book ai didi

objective-c - 为什么我不在传递给 dispatch_after() 的 block 中使用指向自身的弱指针?

转载 作者:太空狗 更新时间:2023-10-30 03:28:48 24 4
gpt4 key购买 nike

我见过以下使用:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//code to be executed on the main queue after delay
[self doSometingWithObject:obj1 andAnotherObject:obj2];
});

但是它不应该在 block 中使用 weak self 吗?

__weak typeof(self) weakSelf = self;
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//code to be executed on the main queue after delay
[weakSelf doSometingWithObject:obj1 andAnotherObject:obj2];
});

我是 GCD 和 Blocks 的新手,正在尝试找出最正确的用法。非常感谢您对此的任何指导。

最佳答案

这取决于所需的行为。

  • 第一个语法(引用 block 中的 self)将保持对 View Controller 的强引用,直到 dispatch_after 触发并且 doSometingWithObject 成功运行。即使与该 View Controller 关联的 View 在此期间被取消,也会发生这种情况。

    因此,只有在绝对需要运行该方法的情况下,您才会使用此模式,即使在与该 View Controller 关联的 View 被关闭之后也是如此。例如,如果该方法正在更新一些模型对象、将某些内容保存到持久存储、发布一些网络请求等。

  • 第二种语法(weakSelf 模式)不会保持对 View Controller 的强引用,因此如果与 View Controller 相关联的 View 在 block 时被取消运行时, View Controller 将被释放并且 weakSelf 将为 nil,因此 doSometingWithObject 将不会被调用。 (显然,如果 View 还没有被关闭, View Controller 就不会被释放,weakSelf 不会是 nil 并且那个方法会被调用。)

    如果所讨论的方法只需要在 View 尚未被关闭时调用,那么您将执行此操作。例如,如果该方法的唯一目的是更新该 View 上的某些 UI 对象,那么如果 View 已经被关闭,您显然不需要调用该方法。在这种情况下,您通常更喜欢使用 weakSelf,以便在不再需要时立即释放 View Controller 。

  • 为了完整起见,实际上还有这种模式的第三种排列,有时(开玩笑地)称为 weakSelf/strongSelf “舞蹈”:

    __weak typeof(self) weakSelf = self;
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //code to be executed on the main queue after delay
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
    [strongSelf doSomethingWithObject:obj1 andAnotherObject:obj2];
    [strongSelf doSomethingElseWithObject:obj1];
    }
    });

    此模式与第二个示例非常相似,如果 self 被释放,则不会调用方法。当您需要弱引用时可以使用此模式,但是 (a) 您需要确保它在 block 运行时不被释放;或者 (b) 当您需要测试它是否为 nil 时,但又想避免竞争条件。

关于objective-c - 为什么我不在传递给 dispatch_after() 的 block 中使用指向自身的弱指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34751731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com