saveAction called 2 times with notification

Discussion in 'Mac Programming' started by Val K, Jun 25, 2013.

  1. macrumors member

    Joined:
    Dec 19, 2012
    Location:
    Italy
    #1
    I have a custom class for NSButton called `MyButton` where I post a notification for a quicksave
    `MyButton.m`:
    Code:
        -(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`:
    Code:
        - (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
     
  2. macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    Did you register more than one object for that notification?

    In the NSLog statement, log sender and self as well.
     
  3. Val K, Jun 25, 2013
    Last edited: Jun 25, 2013

    thread starter macrumors member

    Joined:
    Dec 19, 2012
    Location:
    Italy
    #3
    no, as you can see there's no specified object, it's "nil".
    this is the log:
    Code:
    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
    Code:
    -(void)awakeFromNib{
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"quickSave" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAction:) name:@"quickSave" object:nil];
    }
     

Share This Page