繁体   English   中英

无法获得保留周期

[英]Can't get retain cycle

我在apple.com上发现了这种tableview延迟加载的代码,但无法获取保留周期,需要创建解析器的弱指针,请帮忙。

ParseOperation *parser = [[ParseOperation alloc] initWithData:self.appListData];

parser.errorHandler = ^(NSError *parseError) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self handleError:parseError];
    });
};
// Referencing parser from within its completionBlock would create a retain
// cycle.
__weak ParseOperation *weakParser = parser;

parser.completionBlock = ^(void) {
    if (weakParser.appRecordList) {
        // The completion block may execute on any thread.  Because operations
        // involving the UI are about to be performed, make sure they execute
        // on the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            // The root rootViewController is the only child of the navigation
            // controller, which is the window's rootViewController.
                RootViewController *rootViewController = (RootViewController*)       [(UINavigationController*)self.window.rootViewController topViewController];

            rootViewController.entries = weakParser.appRecordList;

            // tell our table view to reload its data, now that parsing has completed
            [rootViewController.tableView reloadData];
        });
    }

    // we are finished with the queue and our ParseOperation
    self.queue = nil;
};

[self.queue addOperation:parser]; // this will start the "ParseOperation"

如果您在完成块中引用解析器,则该块将保留它。 并且由于解析器又保留了完成块,因此您将获得一个保留周期:

       parser
      +---------------------------+
      |                           |
      |                           |
      |                           |
 +----+   completion block        |<-------+
 |    |  +---------------------+  |        |
 |    |  |                     |  |        | holds onto
 |    |  |                     |  |        |
 |    |  |                     +-----------+
 +------>|                     |  |
      |  |                     |  |
      |  |                     |  |
      |  |                     |  |
      |  |                     |  |
      |  +---------------------+  |
      |                           |
      +---------------------------+

当您在完成块中使用弱指针时,您会中断此循环,因为完成块不再使解析器无法释放。

暂无
暂无

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

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