iOS 使用巨集定義函式和程式碼塊
阿新 • • 發佈:2019-01-04
iOS使用巨集定義函式和程式碼塊
今天在開發過程中碰到一個問題:就是父類中要向外傳送通知,然後子類中或者其他類中來接收它。當然一般是把它寫到類方法中去,但是有個問題,就是如果呼叫的類不是它的子類,就不能直接呼叫,當然也可以採用靜態方法實現,我這裡主要是想用巨集定義來實現,下面我分別介紹使用巨集定義函式和定義程式碼塊的方式進行,廢話不多說了,直接上程式碼:
- 使用巨集定義函式實現
//定義
#define SendNotification @"SendNotification"
#define sendMessage(msg) \
({\
dispatch_async(dispatch_get_main_queue(), ^{\
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];\
[notificationCenter postNotificationName:SendNotification object :nil userInfo:@{@"msg":msg}];\
});\
})
//使用
sendMessage(@"發個訊息試試");
//有返回的巨集函式定義
#define getSum(a,b) \
({\
(a+b);\
})
//使用
double sum = getSum(M_PI,M_E);
- 使用巨集定義程式碼塊實現
//定義
#define SendNotification @"SendNotification"
#define sendMessage(msg) \
^(){\
dispatch_async(dispatch_get_main_queue(), ^{\
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];\
[notificationCenter postNotificationName:SendNotification object :nil userInfo:@{@"msg":msg}];\
});\
}()
//使用
sendMessage(@"發個訊息試試");
//有返回的巨集程式碼塊定義
#define getSum(a,b)\
^(){\
return a+b;\
}()
//使用
double sum = getSum(M_PI,M_E);
- 寫在最後,當時寫的時候,想到了使用巨集定義的方式,但是在網上找了一圈沒有找到怎麼使用巨集來定義程式碼塊和函式,於是自己通過嘗試實現了,所以在這裡Mark一下,希望能夠幫到遇到同樣問題的人,也為了以後自己忘了能夠查到。