iOS 使用宏定义函数和代码块

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一下,希望能够帮到遇到同样问题的人,也为了以后自己忘了能够查到。
原文地址:https://www.cnblogs.com/Free-Thinker/p/9517210.html