简体   繁体   中英

Passing data between view controllers using protocol and delegate

I am trying to push a string text to viewcontroller 1 from my viewcontroller 2 using protocols and delegate. I am new to this method of passing data so forgive me if I seem ignorant in any way. The string color always return null. I will post the code I have so far and if it helps, im using navigation controller and using the navigation back button to go from ViewController 2 to ViewController 1.

Viewcontroller 2

.h

@protocol PassString <NSObject>
@required
 - (void) setSecondFavoriteColor:(NSString *)string;
 @end
 @interface ViewController2 : UIViewController{
 UIButton *button; 
 NSString *ee
  id <PassString> delegate;
  }
  @property (retain) id delegate;

ViewController 2

.m

@synthesize delegate;   

-(void)button{
ee = @"Blue Color";
[[self delegate] setSecondFavoriteColor:ee];

ViewController 1.h

@interface ViewController1 : UIViewController <PassString>{
NSString*color;
 }
 @property (strong,nonatomic) NSString *color

ViewController 1.m

- (void)setSecondFavoriteColor:(NSString *)string
{
color = string;
NSLog(@"%@",color);
}

Just a couple things I noticed in your code, your property should contain the specified protocol:

@property (retain) id <PassString> delegate;

And at some point in the class that's implementing the delegate methods, you have to assign the delegate to view controller 1. For example:

[viewController2Instance setPassingDelegate:self];

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