RAC 小記(初學(xué)者入門基礎(chǔ)一)

RAC(ReactiveCocoa)就是平常所說的函數(shù)式響應(yīng)式編程,最基本的使用就是對事件的監(jiān)聽

配置RAC環(huán)境:這里聲明一點,最新版本已經(jīng)支持swift,但是OC的程序安裝最新的RAC可能跑步起來,所以大家最好是用2.5.0以下的版本

使用cocoa pods進行集成:

推薦大家在Podfile文件中使用:platform:ios,'8.0'pod'ReactiveCocoa','~>2.1.8'

基本使用:

1.給按鈕添加監(jiān)聽事件

[[self.myButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {

//x代表的是當前這個按鈕的屬性信息

NSLog(@"%@",self.myButton.currentTitle);//這里是處理點擊按鈕之后用戶要做的事情

}];

2.給視圖添加手勢

UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init];

[[gesture rac_gestureSignal] subscribeNext:^(id x) {

self.myView.backgroundColor = [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1.0];

}];

[self.myView addGestureRecognizer:gesture];

3.寫代理,但是只能實現(xiàn)返回值為void的代理方法


self.alertView = [[UIAlertView alloc] initWithTitle:@"測試RAC" message:@"我是RAC" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];

[[self rac_signalForSelector:@selector(alertView:clickedButtonAtIndex:) fromProtocol:@protocol(UIAlertViewDelegate)] subscribeNext:^(RACTuple *tuple) {//tuple是一個集合,tuple.second指的是ButtonAtIndex中button的序號,如果點擊的是取消就是代表的0,如果是點擊的是確定就是代表的是1

NSLog(@"%@",tuple.second);

}];

[self.alertView show];


也可簡化代理方法

[[self.alertView rac_buttonClickedSignal] subscribeNext:^(id x) {

NSLog(@"%@",x);//這里的x代表的就是點擊的哪個按鈕的序號

}];

4.KVO的使用

self.inputStr = @"我是輸入";

[RACObserve(self,inputStr)

subscribeNext:^(NSString *x){

NSLog(@"%@",x);//發(fā)送一個請求

}];

5.通知的實現(xiàn)

RAC中的通知不需要remove observer,因為在rac_add方法中他已經(jīng)寫了remove。

注冊接收通知:

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"arrayDataPost" object:nil] subscribeNext:^(NSNotification *notification) {

NSLog(@"%@",notification);

}];

發(fā)送通知:

[[NSNotificationCenter defaultCenter] postNotificationName:@"arrayDataPost" object:dict];

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容