代码改变世界

IOS如何解决强引用中的循环引用

2018-09-26 16:36  zhaosn  阅读(846)  评论(0编辑  收藏  举报

一个对象中强引用了block,在block中又强引用了该对象,就会发射循环引用。

解决方法:

1、

 __typeof (&*self) __weak weakSelf = self;
    [UIView animateWithDuration:_animationDuration animations:^{
        CGRect frame = weakSelf.menuView.frame;
        frame.origin.y = -40 - _separatorHeight;
        weakSelf.menuWrapperView.frame = frame;
    } completion:nil];

2、

 __weak CCBluetoothDevice * weakSelf = self;
    
    [weakSelf.OTATimer invalidate];
    weakSelf.OTATimer = nil;

3、

id __block weakSelf = self;

__weak id weakSelf = self;

4、将其中一方强制制空 xxx = nil

 

另外:

__weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
        NSURL *portraitUrl = [NSURL URLWithString:strUrl];
        __block UIImage *protraitImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:portraitUrl]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            if (protraitImg!=nil) {
                strongSelf.portraitImageView.image = protraitImg;
            }
        });
    });