ReactiveCocoa是基于响应式编程的实践,使用起来很方便,下面将讲解详细使用。
1.监听对象的成员变量变化,当成员变量值被改变时,触发做一些事情.
A)普通属性
@property(nonatomic,copy) NSString *changeinput;
[RACObserve(self, changeinput) subscribeNext:^(id x) {
NSLog(@"成员变量 changeinput 被修改成了:%@", x);
}];
当在其他地方修改了changeinput的属性值,将会调用。
B)如何监听控件的值变化,
[[self.textfiled.rac_textSignal
filter:^(NSString *str) {
if (str.integerValue > 30) {
return YES;
} else {
return NO;
}
}]
subscribeNext:^(NSString *str) {
NSLog(@"textfield 控件变化了:%@",str);
}];
2. 属性绑定,转换数据流
A)
//直接绑定
RAC(self.loginButton,enabled) = RACObserve(self,isCanLogin);;
//需要转换数据流,让输入和alpha绑定,当输入为12时,透明度为1.0 否则是0.5
RACSignal *changeSignal = RACObserve(self,changeinput);
RAC(self.loginButton, alpha) = [changeSignal
map:^id(NSString *str) {
return [str isEqualToString:@"12"] ? @1.0 : @0.5;
}];
B)两个输入,按钮之间的绑定关系,当输入长度大于5时,按钮可点击
RACSignal *validUsernameSignal = [self.textfiled.rac_textSignal map:^id(NSString *text) {
return @(text.length >5);
}];
RACSignal *validPasswordSignal = [self.passwordTextfield.rac_textSignal map:^id(NSString *text) {
return @(text.length >5);
}];
RACSignal *signUpActiveSignal = [RACSignal combineLatest:@[validUsernameSignal, validPasswordSignal]
reduce:^id(NSNumber *usernameValid, NSNumber *passwordValid){
return @([usernameValid boolValue] && [passwordValid boolValue]);
}];
[signUpActiveSignal subscribeNext:^(NSNumber *signupActive) {
self.loginButton.enabled = [signupActive boolValue];
}];
3.两个控件之间的绑定关系,如输入框输入,label显示输入结果
RAC(self.outputLabel,text) = self.textfiled.rac_textSignal;
或者也可以和一个属性值绑定,当changeinput改变时,outputLabel也会发生改变,
RAC(self.outputLabel, text) = RACObserve(self, changeinput);
4.事件监听
- (void)eventListener{
RACSignal *buttonSignal = [self.signalButton rac_signalForControlEvents:UIControlEventTouchUpInside];
[buttonSignal subscribeNext:^(id x) {
NSLog(@"buttonSignal %@",buttonSignal);
}];
RACSignal *textChange = [self.passwordTextfield rac_textSignal];
[textChange subscribeNext:^(NSString *textfield)
{
NSLog(@"textfield %@", textfield);
}];
RACSignal *viewAppeared = [self rac_signalForSelector:@selector(viewDidAppear:)];
[viewAppeared subscribeNext:^(id x) {
NSLog(@"viewDidAppear %@", x);
}];
}
5.其它的一些用法
如,
A)添加观察者
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"MyNotification" object:nil] subscribeNext:^(NSNotification *notification) {
NSLog(@"Notification Received");
}];
B)object的dealloc被触发时,执行的一段代码,这样很方便吧
NSArray *array = @[@"foo"];
[[array rac_willDeallocSignal] subscribeCompleted:^
{
NSLog(@"will dealloc");
}];
array = nil;