ReactiveObjC(OC版ReactiveCocoa)的安装与使用
https://github.com/ReactiveCocoa/ReactiveObjC/blob/master/README.md#when-to-use-reactiveobjc
一、使用pod导入第三方库ReactiveCocoa
podfile文件内容如下:
platform :ios,'8.0'
target 'MyReactiveCocoa'do
use_frameworks!
pod 'ReactiveObjC','~> 3.1.0'
end
二、基础用法
1、将页面元素和数据绑定
// When self.username changes, logs the new name to the console.
//
// RACObserve(self, username) creates a new RACSignal that sends the current
// value of self.username, then the new value whenever it changes.
// -subscribeNext: will execute the block whenever the signal sends a value.
@weakify(self)
[RACObserve(self.person, name)
subscribeNext:^(id x){
@strongify(self)
self.lblName.text = x;
}];
2、定制条件约束信号量发出的情况
// Only logs names that starts with "j".
//
// -filter returns a new RACSignal that only sends a new value when its block
// returns YES.
[[RACObserve(self.person, name) filter:^BOOL(NSString *value) {
return [value hasPrefix:@"j"];
}] subscribeNext:^(id_Nullable x) {
self.lblName.text = x;
}];
3、单向绑定
// Creates a one-way binding so that self.createEnabled will be
// true whenever self.password and self.passwordConfirmation
// are equal.
//
// RAC() is a macro that makes the binding look nicer.
//
// +combineLatest:reduce: takes an array of signals, executes the block with the
// latest value from each signal whenever any of them changes, and returns a new
// RACSignal that sends the return value of that block as values.
RAC(self, createEnabled) = [RACSignal combineLatest:@[ RACObserve(self, password), RACObserve(self, passwordConfirmation) ]
reduce:^(NSString *password, NSString *passwordConfirm) {
return @([passwordConfirm isEqualToString:password]);
}];
3、给button添加点击事件
// Logs a message whenever the button is pressed.
//
// RACCommand creates signals to represent UI actions. Each signal can
// represent a button press, for example, and have additional work associated
// with it.
//
// -rac_command is an addition to NSButton. The button will send itself on that
// command whenever it's pressed.
self.button.rac_command = [[RACCommand alloc] initWithSignalBlock:^(id _) {
NSLog(@"button was pressed!");
return [RACSignal empty];
}];
4、