简体   繁体   中英

Can't get retain cycle

I found this code of tableview lazyloading from apple.com,but can't get the point of retain cycle,what's the need of creating weak pointer of parser,please help.

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"

If you reference the parser in the completion block, the block will retain it. And since the parser in turn holds onto the completion block, you get a retain cycle:

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

When you use a weak pointer in the completion block, you break this cycle, since the completion block no longer keeps the parser from being deallocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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