简体   繁体   中英

is this a retain cycle in Objective C?

I've declared a property on my UICollectionViewCell like this:

@property (nonatomic, copy) void(^onSelection)(BOOL selected);

I override -setSelected: like this:

- (void)setSelected:(BOOL)selected {
    [super setSelected:selected];

    if (self.onSelection != NULL) {
        self.onSelection(selected);
    }
}

Then in -cellForItemAtIndexPath: i configure like this

cell.onSelection = ^(BOOL selected) {
    //the compiler is telling me this might be a retain cycle but i dont think so...
    cell.tintColor = [UIColor redColor];
};

Is this a retain cycle?

Thanks!

Yes it is. Instead you should use a weak+strong combo.

__weak typeof(cell) weakCell = cell;
cell.onSelection = ^(BOOL selected) {
    __strong typeof(weakCell) strongCell = weakCell;
    //the compiler is telling me this might be a retain cycle but i dont think so...
    strongCell.tintColor = [UIColor redColor];
};

In your particular case you don't even need this block because you can update cell in subclass inside of setSelected: or handle tableView:didSelectRowAtIndexPath: in your table view controller.

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