简体   繁体   English

使用协议和委托在视图控制器之间传递数据

[英]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. 我试图使用协议和委托从我的viewcontroller 2将字符串文本推送到viewcontroller 1。 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. 字符串颜色始终返回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转到ViewController 1。

Viewcontroller 2 Viewcontroller 2

.h 。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 ViewController 2

.m .m

@synthesize delegate;   

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

ViewController 1.h ViewController 1.h

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

ViewController 1.m 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: 在实现委托方法的类中的某个时刻,您必须将委托分配给视图控制器1。例如:

[viewController2Instance setPassingDelegate:self];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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