zoukankan      html  css  js  c++  java
  • 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一下,希望能够帮到遇到同样问题的人,也为了以后自己忘了能够查到。
  • 相关阅读:
    [linux] 将socket设置为非阻塞(nonblocking)
    翻译—IvorHorton的Begining Visual C++ 2005 [第一章]
    深入解析ATL(第二版ATL8.0)(1.11.3节)
    gdb使用初步
    编程其实就是一个不断做出选择的过程
    windows和linux下多线程的一些区别
    makefile编写入门
    深入解析ATL(第二版ATL8.0)(1.41.7节)
    深入解析ATL(第二版ATL8.0)(1.81.10节)
    用gdb调试子进程
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/9517210.html
Copyright © 2011-2022 走看看