前言
程序启动时在viewDidLoad中执行a=b+c,a=b+c表示将表达式的结果赋给a,而之后改变b或c的值不会影响a,除非在别的方法中进行刷新操作。但在响应式编程中,a的值会随着b或c的更新而更新。
使用场景
在MVC软件架构中,响应式编程允许将相关模型的变化自动反映到视图上,反之亦然。
典型框架
ReactiveCocoa ReactiveCocoa介绍与使用
例子
创建ResponseToolClass类
#import typedef void(^responseBlock)(NSUInteger integerB , NSUInteger integerC);
@interface ResponseToolClass : NSObject
- (void)addIntegerB:(NSUInteger)integerB integerC:(NSUInteger)integerC;
- (void)results:(responseBlock)response;
@end
#import "ResponseToolClass.h"
@interface ResponseToolClass ()
@property (nonatomic , strong) void(^saveResponseBlock)(NSUInteger integerB , NSUInteger integerC);
@end
@implementation ResponseToolClass
- (void)addIntegerB:(NSUInteger)integerB integerC:(NSUInteger)integerC{
self.saveResponseBlock(integerB, integerC);
}
- (void)results:(responseBlock)response{
self -> _saveResponseBlock = [response copy];
}
@end
在ViewController中调用
@interface ViewController ()@property (nonatomic , strong) ResponseToolClass * toolClass;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
__block NSUInteger integerA;
[self.toolClass results:^(NSUInteger integerB, NSUInteger integerC) {
integerA = integerB + integerC;
NSLog(@"%ld",integerA);
}];
};
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSUInteger integerB = arc4random() % 101;
NSUInteger integerC = arc4random() % 10;
[self.toolClass addIntegerB:integerB integerC:integerC];
}
- (ResponseToolClass *)toolClass{
if (!_toolClass) {
_toolClass = [[ResponseToolClass alloc] init];
}
return _toolClass;
}
此时点击屏幕,integerA随着点击,值在随着变化。即响应式编程思想
代码
文章中的代码都可以在我的GitHub ReactiveObjCDemo 找到