Your for
loop will iterate through the entire sequence almost instantly, which means your inner dispatch_after
calls will all be set near the same time, and so will execute at around the same time, which is what you're seeing.
You would likely be better served in this case with an NSTimer
. Something like this:
Create an NSTimer
property to use:
@property (strong) NSTimer* deletionTimer = nil;
Add these methods to your class:
- (void)startDeletionTimer {
[self killDeletionTimer];
self.deletionTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(deletionTimerFired:) userInfo:nil repeats:YES];
}
- (void)killDeletionTimer {
[self.deletionTimer invalidate];
self.deletionTimer = nil;
}
- (void)deletionTimerFired:(NSTimer*)timer {
NSUInteger numberOfRecords = [array_messages count];
if (!numberOfRecords) {
// None left, we're done
[self killDeleteionTimer];
return;
}
[array_messages removeObjectAtIndex:0];
[self.tableViewMessage deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationTop];
}
Initiate the timer with this:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self startDeletionTimer];
});
This has a few advantages over options using the inner dispatch_after
with a delay. It will gracefully handle changes in the array_messages
array since it's count is checked on each iteration, not assumed at the start. So for example, if you have 30 messages, your whole delete process will take 30 seconds. If a new message is added in that time period, or worse, a message is removed somehow, your app will crash when the last dispatch_after
triggers, since the index and/or row won't exist. Similarly, if the user navigates away from the view, the tableView may be deallocated and you'll crash then.
Another advantage is if in those 30 seconds while it's slowly/painfully showing the records be deleted, the user wants to just move on, you can kill the timer and just delete all the rows at once.