繁体   English   中英

阻塞并保留周期为int变量?

[英]Blocks and retain cycle for int variable?

在下面的代码中,我创建了一个对self的弱引用,以避免保留周期。好吧,问题是xCode给我同样的警告:“在此块中强烈捕获self可能导致“ currentPage”变量的保留周期”,是一个int变量。 当它是非objective-c对象指针类型时,“ currentPage”如何导致保留周期

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

该图显示了奇怪的警告。

在此处输入图片说明

谢谢

答案很简单! 如果变量currentPage是视图控制器的ivar,则访问此变量的实际结果将类似于

self->currentPage

这显然导致保持自我。

两种可能的解决方案:

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

要么

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

更新

根据下面的可爱评论,我更新了代码。 确实,Apple推荐使用自成一体的方式工作。

currentPage似乎是一个ivar,因此您会得到警告-因为访问ivar需要隐式的self。

将有两种解决方案,它们并不严格相等:

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

要么

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

请尝试以下方法:

__unsafe_unretained typeof(self) weakSelf = self

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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