IOS传值--代理传值,block传值,NSNotificationCenter传值

一:利用代理传值,就是利用代理进行通信。

接口文件:

#import <Foundation/Foundation.h>

 

@protocol Cdelegate <NSObject>

 

-(void)change:(NSString *)name;

 

 

 

@end

 

.h文件

 

@interface ViewController : UIViewController<Cdelegate>

 

.m文件

- (IBAction)pushBB:(id)sender {

    BViewController *bc=[[BViewController alloc]initWithNibName:@"BViewController" bundle:[NSBundle mainBundle]];

    bc.delegate=self;

    [self presentViewController:bc animated:YES completion:nil];

 

}

 

BViewController文件

.h文件

#import "ViewController.h"

#import "Cdelegate.h"

 

 

@interface BViewController : ViewController

 

@property (weak, nonatomic) IBOutlet UITextField *name;

@property(nonatomic,assign)id<Cdelegate> delegate;

@property(nonatomic,copy)ablock block;

- (IBAction)popBB:(id)sender;

@end

 

.m文件

- (IBAction)popBB:(id)sender {

    [self.delegate change:self.name.text]; 

    [self dismissViewControllerAnimated:YES completion:nil];

}

二:block传值

typedef void (^ablock)(NSString *str);

@property(nonatomic,copy)ablock block;

 

- (IBAction)popBB:(id)sender {

    //[self.delegate change:self.name.text];

    self.block(self.name.text);

    [self dismissViewControllerAnimated:YES completion:nil];

}

 

 

 

- (IBAction)pushBB:(id)sender {

    BViewController *bc=[[BViewController alloc]initWithNibName:@"BViewController" bundle:[NSBundle mainBundle]];

    bc.block=^(NSString *str){

        self.aname.text=str;

    };

    [self presentViewController:bc animated:YES completion:nil];

 

}

 

三:通知

 

   NSDictionary *dic=[NSDictionary dictionaryWithObject:self.name.text forKey:@"name"];

    

    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeText" object:self userInfo:dic];

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

 

       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeText:) name:@"changeText" object:nil];

 

}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。