今天研究了一些AFN中的一些代碼 ,額外發現了一些有趣的東西,記錄下來方便以后復習和思考.
block的簡寫
這個東西簡直能和swift的self?.block媲美一樣簡介,但是我們先看看三目運算符是怎么工作的:
int x = 3;
int y = (x>0)? : 3;
int z = (x>0)? 2:3;
各位會覺得該代碼中y和z中會打印什么值呢?
y=1,z = 2;
實際上第二條賦值語言只是省略了條件為真的時候的返回參數,這個時候就會返回數值1了,至于為什么是返回1呢?我是這么去查看的:
int y = (x>0)? true : false;
如果這里面為兩個值都為空的時候,就會返回這兩個東西,而true在邏輯上是等于1的,false中邏輯是等于0的,所以如果后面的條件不寫的話,按道理來說是會返回0的,但是由于語法設置不允許我們這么寫,所以如果大家有什么好的方法來測試也可以告訴我,相互學習.
那么,在這個基礎上,我們就可以來判斷閉包的操作了,例如常用的點擊按鈕后,我們要先用if來判斷閉包是否存在,不存在的時候就直接跳過,存在的時候就要執行這個閉包:
if(self.block){
self.block();
}//這是閉包沒有參數的情況,復雜情況也是一個套路就不寫了
然后如果根據我們的三目運算符的話,我們可以把閉包寫成下面這種形式:
!self.block?:self.block():
這句語法的意思是如果self.block存在的時候,就執行self.block..
在afn中它是這樣使用的:
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
嗯,是不是覺得還是可以和swift的語法相比較...另外,在這段代碼中我還看到了url_session_manager_completion_group(),一開始覺得沒有什么,但是后面才發現原來這里是用()來調用的啊,是C的函數嗎???
然后我里面一戳...
靜態類單例的寫法
static dispatch_queue_t url_session_manager_processing_queue() {
static dispatch_queue_t af_url_session_manager_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_url_session_manager_processing_queue;
}
static dispatch_group_t url_session_manager_completion_group() {
static dispatch_group_t af_url_session_manager_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_completion_group = dispatch_group_create();
});
return af_url_session_manager_completion_group;
}
我米有學過C,但感覺這跟java的語法已經很像了,去查看了一下,原來這樣可以形成一種類內部的靜態單例,意思就是不會被外部所訪問的單例寫法,那么我們很自己可以想到如果一個類有有queue和group等東西的時候可以使用該方法來描述,其他對象也可以用該方法來封裝靜態類單例哦
static NSArray * arr(){
static NSArray* arr = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
arr=@[@"abc",@"cba"];
});
return arr;
}
NSLog(@"%@",arr());
///abc,cba