Feliz Joneser
Feliz Joneser

Reputation: 91

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);
}

Upvotes: 4

Views: 1560

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130193

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];

Upvotes: 2

Related Questions