? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 初學RAC(一)
一:簡單介紹RAC
RAC全稱ReactiveCocoa,,RAC是Github上由19人團隊開發(fā)的重量級開源框架督怜,它有四大家族炉奴,分別為Cocoa,objc(OCx項目盡量使用它),swift(純Swift也少使用它谦铃,很難用),Bridge(OC和swift使用他)。可以在日常開發(fā)中簡單粗暴的幫開發(fā)者處理事件士嚎,這些事件常見的有(Target,Delegate,KVO,通知篱竭,時鐘毙籽,網(wǎng)絡異步回調(diào)等)路狮。
二:基于OC語言通過cocopods配置RAC
1.創(chuàng)建一個項目虫啥,我自己命名為RACDemo
2.打開MAC終端配置RAC
三:RAC框架的簡單使用
1:在上寫法之前,我們先看RAC的流程圖奄妨,如下
2.RAC的中RACSingal的兩種寫法
(1)初級寫法
2:裝逼寫法
四:RAC監(jiān)聽幾種控件的寫法
1:監(jiān)聽TextField寫法
-(void)RACofTextField{
? ? UITextField *nameTextField =[[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,50)];
? ? [self.view addSubview:nameTextField];
??[[nameTextField rac_textSignal]subscribeNext:^(NSString * _Nullable x) {
? ? ? ? NSLog(@"%@",x);?
? ? }];
}
2:監(jiān)聽按鈕的寫法
-(void)RACofButton
{
? ? UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
? ? button.frame = self.view.bounds;
? ? [self.view addSubview:button]涂籽;
?? [[button rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
? ? ? ? NSLog(@"%@",x) ;
? ? }];
}
3:監(jiān)聽通知的寫法
-(void)RACofNotification
{
?? [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil]subscribeNext:^(NSNotification * _Nullable x) {
? ? ? ? NSLog(@"%@",x);
? ? }];
}
五:RAC最大的坑是循環(huán)引用,在block里面砸抛,前面不要去使用self, 如果要使用可以用@weakify(self)[用在外面打斷循環(huán)引用], @strongify(self)[用在里面防止控制器銷毀block銷毀];
-(void)RACofTextField{
self.nameTextField =[[UITextField alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,50)];
? ? [self.view addSubview:nameTextField];
@weakify(self)
??[[self.nameTextField rac_textSignal]subscribeNext:^(NSString * _Nullable x) {
????@strongify(self)
?????NSLog(@"%@",x);?
? ? }];
}