简体   繁体   中英

Blocks and retain cycle for int variable?

In following code I've created a weak reference to self to avoid retain cycle .Ok The problem is that xCode gives me the same warning "capturing self strongly in this block is likely to lead to a retain cycle" for "currentPage" variable which is an int variable. How come "currentPage" lead to a retain cycle while it is a non objective-c object pointer type

__weak CoresspondenceDetailsViewController *weakself = self;
[tableViewBackground.tableView addInfiniteScrollingWithActionHandler:^
 {
    [weakself getPrivateCorrespondencesForPage:currentPage];
 }

image showing the strange warning.

在此处输入图片说明

thank you

The answer is easily! If your variable currentPage is ivar of your view controller then the actual result of accessing this variable will be look like

self->currentPage

which is obviously lead to retaining of self.

Two possible solutions:

__weak CoresspondenceDetailsViewController *weakSelf = self;
int page = currentPage;
[tableViewBackground.tableView addInfiniteScrollingWithActionHandler:^
{
  CoresspondenceDetailsViewController *strongSelf = weakSelf;
  if (strongSelf) {
    [strongSelf getPrivateCorrespondencesForPage:page];
  }
}

or

__weak CoresspondenceDetailsViewController *weakSelf = self;
[tableViewBackground.tableView addInfiniteScrollingWithActionHandler:^
{
  CoresspondenceDetailsViewController *strongSelf = weakSelf;
  if (strongSelf) {
    [strongSelf getPrivateCorrespondencesForPage:strongSelf->currentPage];
  }
}

I updated code, according the lovely comments below. Indeed, it's recommended by Apple way of working with self in blocks.

currentPage seems to be an ivar, thus you get the warning - since accessing an ivar requires an implicit self.

There would be two solutions, which are not strictly equal:

__weak CoresspondenceDetailsViewController *weakself = self;
[tableViewBackground.tableView addInfiniteScrollingWithActionHandler:^
 {
    CoresspondenceDetailsViewController* strongSelf = weakSelf;
    [strongSelf getPrivateCorrespondencesForPage:strongSelf.currentPage];
 }

or

NSInteger cp = self.currentPage;
__weak CoresspondenceDetailsViewController *weakself = self;
[tableViewBackground.tableView addInfiniteScrollingWithActionHandler:^
 {
    CoresspondenceDetailsViewController* strongSelf = weakSelf;
    [strongSelf getPrivateCorrespondencesForPage:cp];
 }

请尝试以下方法:

__unsafe_unretained typeof(self) weakSelf = self

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