Search code examples
objective-cautomatic-ref-countingcycle

self.dictionary[blah] = object with block that uses self: creates a ref-count loop in ARC?


I've got a class using ARC that has a member property that's a mutable dictionary. I then set a value for a key in that dictionary. That value is an object holding a block that references self for the object.

- (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
    self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
        ^(DoLaterThingie *dlt) {
            [self.log addObject:@"Did Thingie!!!"]
        }
    ];
}

Have I created a ref-count cycle? It's a bit of a contrived example, but essentially captures what I'm doing. I've managed to wrap my brain about the simple case, but not sure how deep these cycles can go.


Solution

  • You have to create a weak self to prevent the retain cycle.

    - (void)doSomethingLaterWithVar:(id)var forSlot:(id)slot {
        __weak id weakSelf = self;
        self.doThingsLater[slot] = [DoLaterThingie doAfterNSecs: 5 block:
            ^(DoLaterThingie *dlt) {
                [weakSelf.log addObject:@"Did Thingie!!!"]
            }
        ];
    }
    

    In a block, if you don't use a weak self, self will hold on to the block and the block will hold on to self and neither will be deallocated.