【问题标题】:numberOfRowsInSection called before openWithCompletionHandler blocknumberOfRowsInSection 在打开 WithCompletionHandler 块之前调用
【发布时间】:2013-08-17 10:53:41
【问题描述】:
 - (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];
}

在 openWithCompletionHandler 的块之前调用 numberOfRowsInSection。
[self.list count] 为 nil,为什么?

【问题讨论】:

    标签: objective-c uitableview core-data


    【解决方案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];
    }];
    

    【讨论】:

    • 如果我想改变self.list,我应该放弃这个块吗?有什么解决办法吗?
    • 很高兴能帮上忙 :)
    猜你喜欢
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    相关资源
    最近更新 更多