block,代理,通知傳值

weixin_33935777發表於2017-07-20

A->B B返回值給A;

B.h檔案----------------------
//代理
@protocol returnDelegate <NSObject>

  • (void)returnText:(NSString *)str;

@end
//用typedef 定義block
typedef void (^returnBlock)(NSString *);

@interface OneViewController : ViewController
//將block定義為屬性
@property (nonatomic,copy)void(^myblcok)(NSString *);
//typedef定義的block
@property (nonatomic,copy)returnBlock blcok;
//代理
@property (nonatomic,weak) id<returnDelegate> delegate;

@end

B.m

  • (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //屬性block傳
    self.myblcok(@"第一");
    //typ Block傳
    self.blcok(@"第二");

//代理傳
if ([self.delegate respondsToSelector:@selector(returnText:)]) {
[self.delegate returnText:@"第三"];
}

通知傳
[[NSNotificationCenter defaultCenter] postNotificationName:@"textName" object:self userInfo:@{@"text":@"第四"}];

[self.navigationController popViewControllerAnimated:YES];

}

A.m

  • (void)viewDidLoad {
    [super viewDidLoad];

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

  • (void)notice:(NSNotification*)not{
    self.lable4.text = not.userInfo[@"text"];

}

  • (IBAction)btnClcik:(UIButton *)sender {
    __weak typeof (self) weakSelf = self;

    OneViewController *vc = [OneViewController new];
    [vc setMyblcok:^(NSString *str) {
    weakSelf.lable1.text = str;
    }];

    vc.blcok = ^(NSString *str2){

      weakSelf.labletow.text = str2;
    

    };
    vc.delegate = self;

    [self.navigationController pushViewController:vc animated:YES];

}

  • (void)returnText:(NSString *)str{

    _lable3.text = str;
    }

相關文章