#pragma clang diagnostic ignored 作用

本文介绍了#pragma clang diagnostic ignored在编译过程中的作用,主要用于整理代码和抑制编译器警告。通过示例展示了如何忽略非空检查警告和方法弃用告警,帮助开发者更好地管理和控制编译过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们首先要搞清楚的是:作为预处理指令,#pragma 在编译时进行计算。但它并不像如 #ifdef…#endif 之类的宏,#pragma 的使用方式不会改变你的应用运行时的行为。相反的,#pragma 声明主要由 Xcode 用来完成两个主要任务:整理代码和防止编译器警告。

我相信大家都用过 #pragma mark来在划分代码模块,使代码更整洁、逻辑更清晰。例如:

@implementation ViewController

- (id)init {
  ...
}

#pragma mark - UIViewController

- (void)viewDidLoad {
  ...
}

#pragma mark - IBAction

- (IBAction)cancel:(id)sender {
  ...
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  ...
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  ...
}

#pragma mark十分主流,但是另一方面,用#pragma声明来防止来自编译器或者静态分析器的警告是我们平时比较少用的。使用的姿势是这样的:

#pragma clang diagnostic push  
#pragma clang diagnostic ignored "-需要忽略的命令"  
    // 可能会报警的代码。  
#pragma clang diagnostic pop  

常见的使用有:
1,忽略参数非空检查(”-Wnonnull”),我们的头文件这样定义:

-(instancetype _Nullable)initWithUrl:(NSString *_Nonnull)url param:(NSDictionary *_Nullable)param NS_DESIGNATED_INITIALIZER;

在我们的实现文件中,累的初始化方法:

- (instancetype)init{
#pragma clang diagnostic push 
#pragma clang diagnostic ignored "-Wnonnull"
    return [self initWithUrl:nil param:nil];
#pragma clang diagnostic pop
}

2,方法弃用告警(”-Wdeprecated-declarations”)

#pragma clang diagnostic push    
#pragma clang diagnostic ignored "-Wdeprecated-declarations"         
[TestFlight setDeviceIdentifier:[[UIDevice currentDevice] uniqueIdentifier]];    
#pragma clang diagnostic pop     

其他还有一些不太常用的选项,大家可参考:
http://blog.youkuaiyun.com/a466468841/article/details/50751503

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值