the Reverend
the Reverend

Reputation: 12579

How to implement something like UITableView reloadData

I have a custom control with a a data source similar to how a UITableView works. I have also added a reloadData function to load new data.

I want the reload data implementation to be called once per run loop, to avoid reloading the same data more than once.

This is my current implementation:

func reloadData(){
    guard reloadDataScheduled == false else{
        return
    }

    self.reloadDataScheduled = true
    NSRunLoop.currentRunLoop().performSelector("innerReloadData", target: self, argument: nil, order: 0, modes: [NSDefaultRunLoopMode])
}

The innerReloadData is a private function which actually does the loading, and sets the reloadDataScheduled to false.

This seems to work most of the times, but other instances it seems to delay more than 2 seconds, which is not what I want.

I need insight into the delay of the runloop or any advice on how to achieve this style of implementation.

Upvotes: 1

Views: 245

Answers (1)

TopChul
TopChul

Reputation: 459

I usually use below code in this case.

- (void)setNeedsReloadData
{
    // cancel all previous schedules
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];

    // below codes schedule "immediately run after current fetching on runloop"
    [self performSelector:@selector(reloadData) withObject:nil afterDelay:0];
}
- (void)reloadData
{
    // cancel the others schedules
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];

    // Reload Data
    ...
}

U can call -[XXX setNeedsReloadData] any time and any times. reloadData will run once per fetching on runloop.

ps. in SWIFT

  • before swift 1.1 - [NSObject performSelector: withObject: afterDelay:] was prevented.
  • after swift 2.0 - Now it is permitted.

Upvotes: 3

Related Questions