• 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一下,希望能够帮到遇到同样问题的人,也为了以后自己忘了能够查到。
  • 相关阅读:
    mac 使用指南
    客服系统引用方案
    CSS中margin和padding的区别
    NuGet学习笔记(1)——初识NuGet及快速安装使用
    百度搜索这些词:(百度搜索特效,好玩)
    sql语言:如何查询字符串某个字符的个数?
    Sql日期时间格式转换
    SQL获取当前时间(日期)
    Redis快速入门:初识Redis
    选择Key-Value Store
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/9517210.html
Copyright © 2020-2023  润新知