LoginSignup
59
59

More than 5 years have passed since last update.

[UITableView]reloadDataの完了後に処理を無理なく行いたい

Posted at

やりたかったこと:例


// UITableViewのdataSourceを変更する
……

// dataSource変更後のNSIndexPathを作成する
[NSIndexPath indexPathForRow:row inSection:section];

// 新しいdataSourceに反映させたあとでスクロールさせたい
[_tableView  reloadData]
[_tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];

でやってしまうと、scrollToRowAtIndexPathが呼ばれるときは
reloadDataが完了される前のdataSourceで実行されてしまう。
だからといってNSThreadで待ったり、フラグだNotificationだするのはナンセンス

解決方法:UITableViewの拡張

@implementation UITableView (UITableViewAddition)

-(void)reloadDataAndWait:(void(^)(void))waitBlock {
    [self reloadData];
    if(waitBlock){
        waitBlock();
    }
}
@end

使用方法:例

NSLog(@"numberofsection%d",_tableView.numberOfSections);

[_tableView  reloadDataAndWait:^{
    NSLog(@"numberofsection%d",_tableView.numberOfSections);
    [_tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}];

ちゃんとreload後に処理されていることがわかる。

参考にしたURL
http://stackoverflow.com/questions/15218861/call-function-only-after-reloaddata-has-finished

59
59
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
59
59