Karen
Karen

Reputation: 169

Passing string from second view controller to first controller

I am trying to send string from Second VC to First VC. I have assigned delegate to first VC and given protocol in second VC but I don't see the method in First VC is being called when Second VC sends some data.

Code

First VC

FirstViewController.h

#import <UIKit/UIKit.h>
#import "SecondViewController.h"

@interface FirstViewController : UIViewController <cellDelegate>

@end

FirstViewController.m

- (void)printString:(NSString *)string{
    NSLog(@"Received string: %@",string);
}

SecondViewController.h

@protocol cellDelegate <NSObject>
- (void)printString:(NSString *)string{
@end

@interface SecondViewController : UIViewController
@property (nonatomic, weak) id <cellDelegate> delegate;
@end

SecondViewController.m

- (IBAction)buttonPressed:(id)sender {
    if ([self.delegate respondsToSelector:@selector(printString:)]) {
            [self.delegate printString:@"arrow"]];
        }
}

Any help is greatly appreciated.

Upvotes: 0

Views: 216

Answers (3)

Nidhi Patel
Nidhi Patel

Reputation: 1292

When you navigate from one VC to Second VC you can set the delegate.

SecondViewcontroller *secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewcontroller"];
secondVC.delegate = self;
[self.navigationController pushViewController:secondVC animated:YES];

This code writes on FirstViewController. Hope it helps you.

Upvotes: 1

Lenin
Lenin

Reputation: 685

You forgot to do

SecondViewcontroller *vc;

vc.delegate=self;

On first view controller

Upvotes: 1

alegelos
alegelos

Reputation: 2604

Maybe you just forgot to assign your secondViewController.delegate to self.

1- In first viewController, before pushing secondViewController, with that SecondViewController instance do:

secondViewController.delegate = self;

I can not comment, so if this does not work out just let me know or share more code.

Upvotes: 1

Related Questions