Passing data into the ViewController using the back button

ios, objective-c, xcode

Solution

You want to define a delegate in ViewB and implement it in ViewA. At the appropriate time (e.g., when the back button is tapped) ViewB call the delegate method, passing the value as a parameter.

Something like this:

ViewB.h

// Define a delegate protocol allowing 
@protocol ViewBDelegate

// Method of delegate called when user taps the 'back' button
-(void) backButtonSelected:(id) object;

@end


@interface ViewB : UIViewController

// property to hold a reference to the delegate
@property (weak)id<ViewBDelegate> delegate;

-(IBAction)backButtonSelected:(id)sender;

@end

ViewB.m:

@implementation ViewB

...

-(IBAction)backButtonSelected:(id)sender{
    NSObject *someObjectOrValue = nil;

    // Invoke the delegates backButtonSelected method, 
    // passing the value/object of interest
    [self.delegate backButtonSelected:someObjectOrValue];
}

@end

ViewA.h:

#import "ViewB.h"


//  The identifier in pointy brackets (e.g., <>) defines the protocol(s)
// ViewA implements
@interface ViewA : UIViewController <ViewBDelegate>

...

-(IBAction)someButtonSelected:(id)sender;

@end

ViewA.m:

-(IBAction) someButtonSelected:id @implementation ViewA

...

// Called when user taps some button on ViewA (assumes it is "hooked up" 
// in the storyboard or IB
-(IBAction)someButtonSelected:(id)sender{

    // Create/get reference to ViewB.  May be an alloc/init, getting from storyboard, etc.
    ViewB *viewB = // ViewB initialization code

    // Set `ViewB`'s delegate property to this instance of `ViewA`
    viewB.delegate = self;
    ...
}

// The delegate method (defined in ViewB.h) this class implements
-(void)backButtonSelected:(id)object{
    // Use the object pass as appropriate
}

@end

Problem

I have multiple buttons in ViewA. When a button is clicked, it is redirected to ViewB. In ViewB, the user does some interactions, and then clicks the back button when he is done. How do I run a method and pass in a parameter from ViewB into ViewA and then continue working in ViewA? Using the back button is strongly required, but I am keen to learn if there are other ways. My idea was to get the ViewA from the stack, and when I am done with ViewB, just call upon it and redirect, but I couldn't figure out how to do it. Thank you.

Original source