控制器之间反向传值

控制器之间反向传值

  • 委托(代理)

    • 首先我们定下一个协议protocol

      1.    #import <Foundation/Foundation.h>
      2.
      3. @protocol ChangeText <NSObject>
      4.
      5. -(void)changeText:(NSString *)str;
      6. @end
    • 控制器a遵守协议ChangeText,并实现协议的方法,控制器b公开自己的一个遵守协议ChangeText的属性delegate,在控制器a的视图转到控制器b的视图时,b.delegate = a; 由b返回到a是b.delegate调用协议方法。

      1.    SecondViewController *controller = [[SecondViewController alloc] init];
      2.// 方法一: 委托
      3.controller.delegate = self;
      4.
      1.    // 方法一: 协议
      2.if (self.delegate) {
      3. [self.delegate changeText:f.text];
      4.}
      5.
  • block

    • 首先在b的h文件中定义一个block,并定义block为其属性

      1.typedef void(^changeText)(NSString *);
      2.@interface SecondViewController : UIViewController <UITextFieldDelegate>
      3.@property (nonatomic,copy) changeText ct;
      4.@end
    • a转向b需要做的事(实现block)

      1.    //方法二: block
      2. controller.ct = ^(NSString *str){
      3. ((UILabel *)[self.view viewWithTag:1024]).text = str;
      4. };
      5.
    • b返回a需要做的事

      1.    // 方法二: Block
      2. self.ct(f.text);
  • 单例
    • 在整个程序中定义个单例对象,对单例对象定义一个属性用于保存需要传递的值
    • a转向b需要做的事是在由b返回到a后获取单例对象并取得其保存的b传递的值。
    • b返回a需要做的事是在由b返回到a的时候获取单例对象并对单例对象并赋值需要传递的值
  • 通知中心

    • 在对象销毁时,要注销掉观察者

      1.    -(void)dealloc{
      2. //注销观察者
      3. [[NSNotificationCenter defaultCenter] removeObserver:self];
      4.
      5.}
    • a转向b需要做的事

      1.    //方法三: 通知 (注册观察者,最后需要将观察者注销)
      2. // 参数一: 接收通知的对象
      3. // 参数二: 接收通知后做什么,做什么的参数是notification
      4. // 参数三: 接收的通知名字
      5. // 参数四: 指定接收的通知的发送者
      6. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"A" object:nil];
      7.
    • b返回a需要做的事

      1.    // 方法三: 通知
      2. // 参数一: 通知名字,接收通知的标识
      3. // 参数二: 发送的通知内容
      4. NSNotification *notification = [[NSNotification alloc] initWithName:@"A" object:f.text userInfo:nil];
      5. NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
      6. // 发送通知
      7. [notificationCenter postNotification:notification];
原文地址:https://www.cnblogs.com/buakaw/p/5205603.html