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

前端之家收集整理的这篇文章主要介绍了objective-c – 将self属性传递给block时的ARC实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我最近转移到了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.没什么大不了的,但它使代码更加不言自明.

猜你在找的Xcode相关文章