无法获得保留周期

时间:2013-11-15 12:58:43

标签: ios

我发现这个tableview的代码是从apple.com延迟加载的,但是无法得到保留周期的点,有什么需要创建解析器的弱指针,请大家帮帮忙。

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"

1 个答案:

答案 0 :(得分:1)

如果在完成块中引用解析器,则块将保留它。由于解析器依次保留在完成块上,因此您将获得一个保留周期:

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

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