Domanda

What am I missing here? I'm just trying to send a simple notification from a modal view controller back to the view controller that launched it, but nothing gets received.

This is the code in the view controller that launches the modal segue:

- (IBAction) chooseSuperGroup:(UIButton *)sender {
    NSLog(@"super group choice about to be made");

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(choiceReceived:)
                                                 name:@"selectionMade"
                                               object:self];
}

- (void) choiceReceived: (NSNotification *) notification
{
    NSLog(@"here");
    if ([[notification name] isEqualToString:@"selectionMade"]) {
         NSLog(@"received");
         NSLog(@"%@", (NSString *)[notification userInfo]);
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"selectionMade"
                                                  object:self];
}

Then, over in the modal view controller, this code executes when the user selects a cell from the table view:

NSDictionary *dict = [NSDictionary dictionaryWithObject:selection forKey:@"superGroup"];

NSLog(@"printing dictionary contents");
for (id key in dict) {
    NSLog(@"key: %@   object: %@", key, [dict objectForKey:key]);
}

[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:self userInfo:dict];

My output looks like this:

Super group choice about to be made
printing dictionary contents
key: superGroup   object: myChoice

So the choice is captured and added to a dictionary. But there is no evidence of any notification being received. This can't be that hard, but I'm not seeing my mistake. Can someone help me? Thanks!

È stato utile?

Soluzione

Try using 'nil' instead of 'self'

// Add Observer

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(choiceReceived:) name:@"selectionMade" object:nil];

// Remove Observer

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: @"selectionMade"
                                                  object:nil];

// Post Notification

[[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict];

refer:https://stackoverflow.com/a/8188759/2449268

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top