加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 将self属性传递给block时的ARC实现

发布时间:2020-12-14 17:38:36 所属栏目:百科 来源:网络整理
导读:我最近转移到了ARC,并且在将自身对象传递给块时设置正确的属性值时有点困惑. 根据我的理解,使用_weak声明的任何属性都不应该在dealloc方法中设置为nil.传递给块的自身对象应该使用_weak而不是__block声明. 如果这种理解是正确的,请告诉我,我在下面的实施中正
我最近转移到了ARC,并且在将自身对象传递给块时设置正确的属性值时有点困惑.

根据我的理解,使用_weak声明的任何属性都不应该在dealloc方法中设置为nil.传递给块的自身对象应该使用_weak而不是__block声明.

如果这种理解是正确的,请告诉我,我在下面的实施中正确地做到了这一点.

(void)myApplication {
    self.data = [NSMutableDictionary dictionary];

    __weak MyViewController *aBlockSelf = self;

    [self.data setValue:[MyAction customActionWithBlock:^(MyAction *iAction,NSString *iIdentifier) {
    AnotherViewController *aController = [[AnotherViewController alloc] initWithType:@"aType"];
    aController.hasSearch = NO;
    aController.delegate = aBlockSelf;
        aController.showInventoryImage = YES;
    [aBlockSelf presentNavigationalModalViewController: aController];

    }] forKey:@"aKey"];
}

解决方法

In my understanding,any property declared with __weak should not be set to nil in dealloc method.

是的,你绝对没有理由想要这样做.这不是问题,但它什么都没有.

And self objects passed to a block should be declared with __weak and not __block.

是的,在ARC中,使用__weak可以降低保留周期的风险(a.k.a.强参考周期).将块保存到某个变量(如示例中)或者块异步运行时,这很重要.请参阅“使用Objective-C编程”指南中的Avoid Strong Reference Cycles when Capturing self.

Please let me know if this understanding is correct and I am doing it the right way in the below implementation.

我在你的代码块中唯一的建议是你通常会看到一个名为weakSelf的变量,而不是aBlockSelf.没什么大不了的,但它使代码更加不言自明.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读