ios – 阻止递归和打破保留周期

栏目: IOS · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/14839571/block-recursion-and-breaking-retain-cycle

为了更好的说明这个问题,请考虑以下简单的块递归形式:

__block void (^next)(int) = ^(int index) {
    if (index == 3) {
        return;
    }
    int i = index;
    next(++i);
};
next(0);

XCode(启用ARC)警告“在此块中强烈捕获”可能导致保留周期“.

同意.

问题1:通过将块本身设置为零,保留周期将成功地被破坏:

__block void (^next)(int) = ^(int index) {
    if (index == 3) {
        next = nil; // break the retain cycle
        return;
    }
    int i = index;
    next(++i);
};
next(0);

(注意:你仍然会得到同样的警告,但也许是无理的)

问题2:块递归更好的实现是什么?

谢谢.

为了实现无保留循环的递归块执行,您需要使用两个块引用 – 一个弱和一个强.所以对于你的情况,这是代码可能是什么样子:

__block __weak void (^weak_next)(int);
void (^next)(int);
weak_next = next = ^(int index) {
  if (index == 3) {
    return;
  }
  int i = index;
  weak_next(++i);
};
next(0);

请注意,该块捕获弱块引用(weak_next),并且外部上下文捕获强引用(next)以保持该块.两个引用指向相同的块.

参见 http://stackoverflow.com/a/19905407/1956124 另一个例子,该模式也使用块递归.此外,以下文章的评论部分的讨论也与此相关: http://ddeville.me/2011/10/recursive-blocks-objc/

http://stackoverflow.com/questions/14839571/block-recursion-and-breaking-retain-cycle


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

SCWCD Exam Study Kit Second Edition

SCWCD Exam Study Kit Second Edition

Hanumant Deshmukh、Jignesh Malavia、Matthew Scarpino / Manning Publications / 2005-05-20 / USD 49.95

Aimed at helping Java developers, Servlet/JSP developers, and J2EE developers pass the Sun Certified Web Component Developer Exam (SCWCD 310-081), this study guide covers all aspects of the Servlet an......一起来看看 《SCWCD Exam Study Kit Second Edition》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换