2013-08-17 24 views
0
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    if (self.document.documentState == UIDocumentStateClosed){ 
    [self.document openWithCompletionHandler:^(BOOL success) { 

     self.list = [[Categories getArrayForFirstTable:self.document.managedObjectContext] mutableCopy]; 

    }]; 

} 
[self.tableView reloadData]; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

// Return the number of rows in the section. 
return [self.list count]; 
} 

numberOfRowsInSection調用befor openWithCompletionHandler的塊。
[self.list count]爲零,爲什麼?numberOfRowsInSection之前調用openWithCompletionHandler塊

回答

1

openWithCompletionHandler塊是一個異步操作,根據the apple document

調用此方法開始方法調用的打開和異步讀取原稿的順序。該方法從fileURL屬性獲取文檔的文件系統位置。打開操作結束後,completionHandler中的代碼被執行。

所以你[self.tableView reloadData]將被執行,這將觸發-tableView:numberOfRowsInSection:,你self.list得到有意義的結果之前,通過self.list = [[Categories getArrayForFirstTable:self.document.managedObjectContext] mutableCopy];

該代碼可滿足您的需求:

[self.document openWithCompletionHandler:^(BOOL success) { 
    self.list = [[Categories getArrayForFirstTable:self.document.managedObjectContext] mutableCopy]; 
    // At this point(no matter when), self.list is returned and you can use it. 
    [self.tableView reloadData]; 
}]; 
+0

如果我想改變自我。清單,我應該放棄這個區塊嗎?有一些解決方案? – wmmj23

+0

@ wmmj23請看我更新的回答 – liuyaodong

+0

我是多麼愚蠢......非常感謝你〜 – wmmj23

相關問題