2. RACSubject
-
使用场景
:通常用来代替代理,有了它,就不必要定义代理了。 - 示例代码:
// 1.创建信号
RACSubject *subject = [RACSubject subject];
// 2.订阅信号
//不同的信号订阅的方式不一样!!(因为类型不一样,所以调用的方法不一样)
//RACSubject处理订阅:拿到之前的_subscribers保存订阅者
[subject subscribeNext:^(id x) {
NSLog(@"接受到的数据:%@",x);
}];
//3.发送数据
//遍历出所有的订阅者,调用nextBlock
[subject sendNext:@"我想静静"];
- 实际应用
JJView.h
#import <UIKit/UIKit.h>
#import <ReactiveObjC/ReactiveObjC.h>
@interface JJView : UIView
@property (nonatomic,strong) RACSubject *btnClickSingnal;
@end
JJView.m
-(RACSubject *)btnClickSingnal {
if (!_btnClickSingnal) {
_btnClickSingnal = [RACSubject subject];
}
return _btnClickSingnal;
}
- (instancetype)init {
if (self == [super init]) {
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[button setBackgroundColor:[UIColor redColor]];
[self addSubview:button];
[button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)didClickButton:(UIButton *)btn {
NSLog(@"点了button");
[self.btnClickSingnal sendNext:btn.backgroundColor];
}
SubjectViewController.m
#import "JJView.h"
@interface SubjectViewController ()
@property (nonatomic,strong) JJView *jjView;
@end
@implementation SubjectViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
JJView *view = [[JJView alloc]init];
view.backgroundColor = [UIColor yellowColor];
view.frame = CGRectMake(10, 64, 400, 500);
[view.btnClickSingnal subscribeNext:^(id _Nullable x) {
self.view.backgroundColor = x;
}];
[self.view addSubview:view];
self.jjView = view;
}