1

My project has a design like this:

VC1 ---firstSegue----> VC2 ---secondSegue---> VC3

I have no problem in passing data backward from VC2 to VC1 and VC3 to VC2 by using protocol/delegate method. If I want to pass data from VC3 to VC1 directly, is it possible? OR should I insert a new segue from VC1 to VC3?

=================================== Update ======================================= My situation is when VC3 perform "-viewDidLoad", I want to ask VC1 to perform some action. After the action done, VC3 will continue to work.

1 Answers1

0

Option 1: Use NSUserDefaults to store and retrieve data

Step 1: For Storing

NSUserDefaults in VC3 view controller

[[NSUserDefaults standardUserDefaults] setObject:@"hello" forKey:@"mydata"]; 

Step 2: For Retrieving

NSUserDefaults in VC1 or any other controller:

NSString* receivedData = [[NSUserDefaults standardUserDefaults] objectForKey:@"mydata"];



Option 2: Using delegation and protocols



In VC3.h

@class VC3;

@protocol VC3Delegate <NSObject>
- (void)addItemViewController:(VC3 *)controller didFinishEnteringItem:(NSString *)item;
@end

@interface


@property (nonatomic, weak) id <VC3Delegate> delegate;

In VC3 we call a message on the delegate when we pop the view controller.

NSString *itemToPassBack = @"Pass this value back to VC1";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];

That's it for VC3. Now in VC1.h, tell VC1 to import VC3 and conform to its protocol.

#import "VC3.h"

@interface VC1 : UIViewController <VC3Delegate>

In VC1.m implement the following method from our protocol

- (void)addItemViewController:(VC3 *)controller didFinishEnteringItem:(NSString *)item
{
    NSLog(@"This was returned from VC3 %@",item);
}

The last thing we need to do is tell VC3 that VC1 is its delegate before we push VC3 on to nav stack.

NSMutableArray *arrayOfControllers = [[NSMutableArray alloc] initWithObjects:self.navigationController.viewControllers, nil];

  for (UIViewController *vc in arrayOfControllers) {
    if ([vc isKindOfClass:[VC3 class]]) {
        //It exists
           vc.delegate = self;
    }
bhavya kothari
  • 7,484
  • 4
  • 27
  • 53