2013-11-15 29 views
1

我發現這個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

如果在完成塊中引用解析器,塊將保留它。而且,由於反過來分析器持有到結束塊,你會得到一個保留週期:

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

當您使用在完成塊的一個弱指針,你打破這種惡性循環,因爲完成塊不再保持解析器從被釋放。

+0

感謝您的答案,請你解釋爲什麼塊將保留解析器如果我在完成塊中引用解析器,解析器對象創建在complesion塊外,我是初學者在ios中,請幫助 – user2799156

+0

這很簡單,一塊始終保留您從中引用的對象。否則,他們可以很容易地在塊完成前解除分配。閱讀[Cocoa內存管理指南](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html),這並不難,會讓你的生活更輕鬆。 – zoul

+0

好吧,現在我知道了,非常感謝你。 – user2799156