简体   繁体   中英

Use A delegate to pass data back through multiple view controllers

In IOS, I'm very comfortable with passing data around between views that are directly segued between using prepareforsegue to pass data forward and delegates to pass it back.

The problem I'm having is that I'm building an app that segues through 4 views, then when the user hits enter on the fourth view, I pop the rest of the views to return to the first view controler and it's view, but I can't figure out how to delegate the data back to the first.

I believe the problem lies in setting the delegate in the first view controller. I can't set it like I normally would with segue.destinationviewcontroller because that view controller does not exist yet. Should I set it somewhere else? What is the proper way to do this?

Instead of using delegation for passing the data, consider using NSNotificationCenter to communicate between your view controllers in this situation.

In your first view controller you will register to listen for a notification:

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(handleFourthViewSubmit:)        
                                                 name:@"fourthViewSubmit" 
                                               object:nil];
}

And create the method to be run when the notification is sent:

- (void)handleFourthViewSubmit:(NSNotification *)notification {
    NSDictionary *theData = [notification userInfo];  // theData is the data from your fourth view controller

    // pop views and process theData

}

In your first view controller's dealloc method, be sure to un-register as an observer (to avoid potential crashes):

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

Then in your fourth view controller, broadcast the notification when the enter button is pressed:

// note: dataDict should be an NSDictionary containing the data you want to send back to your first view controller
[[NSNotificationCenter defaultCenter] postNotificationName:@"fourthViewSubmit" 
                                                    object:self 
                                                  userInfo:dataDict];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM