PDA

View Full Version : saveAction called 2 times with notification




Val K
Jun 25, 2013, 05:02 PM
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? Thanks in advance



gnasher729
Jun 25, 2013, 05:34 PM
Via the `NSLog "Saving..."` I see that the saveAction is called 2 times. Why? Thanks in advance

Did you register more than one object for that notification?

In the NSLog statement, log sender and self as well.

Val K
Jun 25, 2013, 05:54 PM
no, as you can see there's no specified object, it's "nil".
this is the log:
Saving...
sender: NSConcreteNotification 0x101915b70 {name = quickSave}
self: <AppDelegate: 0x101927730>
Saving...
sender: NSConcreteNotification 0x101915b70 {name = quickSave}
self: <AppDelegate: 0x1005374c0>
there are two different self. what does it mean?

PS: i've tried this solution but it doesn't work
-(void)awakeFromNib{
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"quickSave" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAction:) name:@"quickSave" object:nil];
}