gpt4 book ai didi

ios - int变量的 block 和保留周期?

转载 作者:行者123 更新时间:2023-11-28 19:06:18 24 4
gpt4 key购买 nike

在下面的代码中,我创建了一个对 self 的弱引用以避免保留循环。好的问题是 xCode 给了我同样的警告“在此 block 中强烈捕获 self 可能会导致保留周期”,因为“currentPage”变量是一个 int 变量。 “currentPage” 是非 objective-c 对象指针类型,怎么会导致保留周期

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

图像显示了奇怪的警告。

enter image description here

谢谢

最佳答案

答案很简单!如果您的变量 currentPage 是 View Controller 的 ivar,那么访问该变量的实际结果将如下所示

self->currentPage

这显然会导致 self 保留。

两种可能的解决方案:

__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 推荐在 block 中使用 self 的方式。

关于ios - int变量的 block 和保留周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20262656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com