Myron Slaw
Myron Slaw

Reputation: 886

What issues could arise when using GCD dispatchAfter() in this use case

I'm going through a book on OS X programing as a refresher and have a document app set up with an array controller, tableView etc. The chapter calls for implementing undo support by hand using NSInvocation. In the chapter, they call for adding a create employee method and manually, adding outlets to the NSArrayController, and connecting my add button to the new method instead of the array controller.

Instead I did this with my method for inserting new objects:

-(void)insertObject:(Person *)object inEmployeesAtIndex:(NSUInteger)index {
NSUndoManager* undoManager = [self undoManager];

[[undoManager prepareWithInvocationTarget:self]removeObjectFromEmployeesAtIndex:index];

if (![undoManager isUndoing]) {
    [undoManager setActionName:@"Add Person"];
}
[self startObservingPerson:object];

[[self employees]insertObject:object atIndex:index];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    // Wait then start editing
    [[self tableView]editColumn:0 row:index withEvent:nil select:YES];
});

}

This works ok (looks a bit silly), but I was wondering the what issues could arise from this. I've done this elsewhere in order to execute code after an animation finished (couldn't figure out a better way).

Thanks in advance.

Upvotes: 0

Views: 81

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90581

Why are you delaying the invocation of -editColumn:row:withEvent:select:?

Anyway, the risks are that something else will be done between the end of this -insertObject:... method and when the dispatched task executes. Perhaps something that will change the contents of the table view such that index no longer refers to the just-added employee.

Upvotes: 1

Related Questions