The log message indicates that two different instances of AppDelegate receive a single notification. Probably you instantiated AppDelegate twice. Ensure you are not manually doing [[AppDelegate alloc] init]
or something, and not putting more than one AppDelegate object in NIB.
Cocoa: saveAction called 2 times with notification
-
01-06-2022 - |
문제
I have a custom class for NSButton called MyButton
where I post a notification for a quicksave
MyButton.m
:
-(void)mouseDown:(id)sender{
[super mouseDown:sender];
[super mouseUp:sender];
[[NSNotificationCenter defaultCenter] postNotificationName:@"quickSave" object:nil userInfo:nil];
}
in AppDelegate
I get the notification for the quick save:
AppDelegate.m
:
- (IBAction)saveAction:(id)sender{
NSLog(@"Saving...");
NSError *error = nil;
if (![[self managedObjectContext] commitEditing]) {
NSLog(@"%@:%@ unable to commit editing before saving", [self class], NSStringFromSelector(_cmd));
}
if (![[self managedObjectContext] save:&error]) {
[[NSApplication sharedApplication] presentError:error];
}
}
-(void)awakeFromNib{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAction:) name:@"quickSave" object:nil];
}
Via the NSLog "Saving..."
I see that the saveAction is called 2 times. Why?
P.S: the notification calls 2 times every function I insert in the selector:
field, so maybe it has to do with the -(void)awakeFromNib{...}
because I see that it's called twice (there are two different self inside the awakeFromNib).
UPDATE: I've "solved" the problem binding in Interface Builder the Application as an AppDelegate delegate and then adding the [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAction:) name:@"quickSave" object:nil];
inside the -(void)applicationDidFinishLaunching:(NSNotification *)aNotification{...}
. I don't know if it's a real solution and obviously it is not an answer to my question (why awakeFromNib is called 2 times), but it might be useful to someone. Does anyone have a clue?
UPDATE2: the right managedobjectcontext is the one called in awakeFromNib
the second time, the first one (identical in awakeFromNib
and applicationDidFinishLaunching
) is wrong.
My app is a statusbar app, the first awakeFromNib is called when i start the app and the second one when a preference window is opened.
해결책