سؤال

I have a modalUIViewController that has a UITableView on it. For whatever cell the user selects, I want to return that text to the previous view controller and dismiss the modal view. I'm using NSNotifications to send the value back. Problem is, my notification is never received.

Here is the code from the 'parent' view:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(choiceReceived:)
                                                 name:@"selectionMade"
                                               object:nil];

    [self performSegueWithIdentifier: @"locationsDetailsSegue" sender: self];
}

- (void) choiceReceived: (NSNotification *) notification
{
    NSLog(@"test");

    NSDictionary *dict = [notification userInfo];
    NSString *user_choice = [dict objectForKey:@"choice"];

    NSLog(@"%@", user_choice);

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

And in the modal view controller:

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *choice = cell.textLabel.text;

    // send a notification of this choice back to the 'parent' controller
    NSDictionary *dict = [NSDictionary dictionaryWithObject:choice forKey:@"choice"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectionMade" object:nil userInfo:dict];

    NSLog(@"%@", [dict objectForKey:@"choice"]);

    [self dismissViewControllerAnimated:YES completion:nil];
}

I get the correct output from the notifier, but I get no output whatsoever from the receiver. Am I missing something obvious? Thanks!

هل كانت مفيدة؟

المحلول

Well, i don't like use NSNotificationCenter in such scenario (Its just my suggestion). I'm always recommend delegate pattern in such case. Delegation pattern working or communicate one-to-one object notification so it give 100% precise output and removing other conflicts.
Create protocol methods in childviewcontroller and delegate property for confirmation in parentclassviewcontroller. Consume chileviewcontroller protocol in parentviewcontroller. Implement required delegate methods of protocol in parentviewcontroller class. Also you can send multiple types of arguments through delegates method. for more info go through this doc.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top