How to pass information from the second Viewcontroller to the first Viewcontroller

Asked

Viewed 331 times

3

I’m having trouble passing along information from the second screen of a NavigationViewController to the first screen of NavigationViewController. On some gringo sites I found teaching to do by Protocol, but it’s not working. There’s an easier and more practical way to do it?

Note: The first screen is a ViewController and the second is a TableViewController that must send the selected cell information to the first screen.

1 answer

3


The direction you should take is just the one you found, through protocol. It’s quite simple and it’s independent if it’s TableViewController or not.

Let’s assume you have the PrimeiraViewController and SegundaViewController. In this second, in your header file .h, create the protocol (before the declaration @interface):

@protocol SegundaViewDelegate <NSObject>
@required
- (void)foo:(id)bar;
@end

And in that same file, the property:

@property (nonatomic, retain) id<SegundaViewDelegate> segundaViewDelegate;

In the implementation file .m, wherever you will pass this value, you call this method:

[self.segundaViewDelegate foo:[NSDate date]]

Here I passed one NSDate example only, of course, but you can create your method as and where you want, in your case it will be when a cell is pressed.

In the PrimeiraViewController, add this delegate to .h:

@interface PrimeiraViewController : UIViewController <SegundaViewDelegate>

And when the second screen is triggered, we set this delegate:

SegundaViewController *viewController = [[SegundaViewController alloc] init];
[viewController setSegundaViewDelegate:self];

And we implemented the method that we will receive the information:

- (void)foo:(id)bar {
    NSLog("%@", bar);
}

See if you can understand and implement it this way.

  • The allocation of 'Segundaviewcontroller' should be done in the prepareForSegue?

  • @Davidbatista This, since you use Storyboard, the allocation is in prepareForSegue: same, just changing to SegundaViewController *viewController = [segue destinationViewController].

  • I believe this was my mistake when I tested it the first time. Later I will make this change and test again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.