views:

68

answers:

1

This is a really strange problem I'm seeing in my app. I have an NSTextField bound to an attribute of an NSManagedObject, but whenever the object is saved the textfield loses focus. I'm continuously updating the value of the binding, so this is far from ideal.

Has anyone seen anything like this before, and (hopefully) found a solution?

+3  A: 

OK, so thanks to Martin for pointing out that I should read the docs a little more closely. This is expected behaviour, and here's what I did to get around it (use your judgement as to whether this is appropriate for you):

I save my context once every 3 seconds, checking at the start if the context has any changes before I bother executing the actual save: method on my NSManagedObjectContext. I added a simple incrementing/decrementing NSUInteger (_saveDisabler) to my Core Data controller class that is modified via the following methods:

- (void)enableSaves {
    if (_saveDisabler > 0) {
        _saveDisabler -= 1;
    }   
}

- (void)disableSaves {
    _saveDisabler += 1;
}

Then all I do in my custom saveContext method is do a simple check at the top:

if (([moc hasChanges] == NO) || (_saveDisabler > 0)) {
    return YES;
}

This prevents the save from occurring, and means that the focus is not stolen from any of my custom textfield subclasses. For completeness, I also subclassed NSTextField and enable/disable saves in my Core Data controller from the following methods:

- (void)textDidBeginEditing:(NSNotification *)notification;
- (void)textDidEndEditing:(NSNotification *)notification;

It might be a little messy, but it works for me. I'm keen to hear of cleaner/less convoluted methods if anyone has done this successfully in another way.

Tony Arnold