简体   繁体   中英

Retain Cycle Even when using Weak/Strong ARC Semantics

`I admit that I am not an expert on ARC and retain cycles though through some research and some great articles (like this ), I believe I get the basics.

However, I am currently stumped. I have a property defined as follows.

@property (nonatomic,retain) Foo *foo;

Inside my init , I do the following.

if(self = [super init]) {

    _foo = [[Foo alloc] initWithDelegate:self];

    // async the rest
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
                                             (unsigned long)NULL), ^(void) {

        __strong typeof(weakSelf) strongSelf = weakSelf;

        if (strongSelf.foo != nil) {
                        [strongSelf.foo runTests];
        }
    });
}
return self;
}

and here is my dealloc

- (void)dealloc {
     _foo = nil;
}

If the dispatch_aync block is commented out, I see my Foo dealloc get called immediately after foo is set to nil . With the block commented in, foo's delloc is not called.

I've got a retain cycle correct? Any idea how?

No, you do not necessarily have a retain cycle (now known as a "strong reference cycle" in ARC). You have code that, if foo existed by the time strongSelf was defined, foo will be retained until the dispatched code finishes.

The only potential strong reference cycle here is the delegate you passed to foo . If that delegate is defined as strong property of the Foo class, then you have a strong reference cycle. If it's defined as a weak property, then you have no strong reference cycle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM