简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM