Nuno Dias
Nuno Dias

Reputation: 3948

Calling A Method With A Delegate in Objective-C (iOS)

I tried to replicade a couple of posts here on stackoverflow, for passing data and make calls with 2 view controllers, but without success.

So I have my ViewController (1st) and EditableViewController (2nd)

When I'm in my EditableViewController (2nd), I click a Button that triggers an IBAction with the method SendTextToViewController. After that, I was expecting for the method didReceiveMessage, in my ViewController (1st) to run, and show me "BANANAS" with NSLog.

Ultimately, I want to send data from my second Controller, to the First Controller.

I'm having a hard time understanding this delegates thing. And I have read a dozen tutorials, videos e documentation trying to figure this out. I think I'm almost there, but can't seem to figure why this is not working.

Can anyone help me please? The code is bellow.

Thank you!

// ViewController.h

#import <UIKit/UIKit.h>

@protocol ViewControllerDelegate <NSObject>

-(void)didReceiveMessage:(NSString *)string;

@end

@interface ViewController : UIViewController <ViewControllerDelegate>;

@end

// ViewController.m

#import "ViewController.h"

@implementation ViewController

-(void)didReceiveMessage:(NSString *)string{
  NSLog(@"BANANAS");
}

@end

// EditableViewController.h

#import <UIKit/UIKit.h>

@protocol ViewControllerDelegate;

@interface EditableViewController : UIViewController

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

@property (nonatomic, weak) IBOutlet UITextField *TextField;
@property (nonatomic, weak) IBOutlet UIButton *SendTextToViewController;

- (IBAction)SendTextToViewController:(id)sender;

@end

// EditableViewController.m

#import "EditableViewController.h"
#import "ViewController.h"

@implementation EditableViewController

@synthesize delegate;
@synthesize TextField;
@synthesize SendTextToViewController;


- (IBAction)SendTextToViewController:(id)sender {
               [delegate didReceiveMessage:TextField.text];
}

- (void)viewDidUnload {
          [self setTextField:nil];
          [super viewDidUnload];
}
@end

Upvotes: 1

Views: 1155

Answers (1)

zrzka
zrzka

Reputation: 21249

You did it in opposite way ... Do this ...

  • create EditableViewControllerDelegate,
  • your ViewController should conform to EditableViewControllerDelegate protocol,
  • assign your ViewController instance as a delegate of EditableViewController instance

Upvotes: 3

Related Questions