iOS中 #pragma clang diagnostic 的常见用法

将警告识别为错误

下面的例子中将-Warc-performSelector-leaks 标记为错误,clang在编译时就会报错。clang会将push和pop范围内的-Warc-performSelector-leaks 都会标记为错误。

- (BOOL)custom_performSelectorWithMethodName:(NSString *)methodName value:(id)value{
 
    if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
        
#pragma clang diagnostic push
#pragma clang diagnostic error "-Warc-performSelector-leaks"
        [self performSelector:NSSelectorFromString(methodName) withObject:value];
#pragma clang diagnostic pop
        return YES;
    }
    return NO;
}

忽略警告

设置忽略某种类型的警告,比如下面忽略-Warc-performSelector-leaks的警告:

- (id)performSelectorWithMethodName:(NSString *)methodName{
    if ([self respondsToSelector:NSSelectorFromString(methodName)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        return [self performSelector:NSSelectorFromString(methodName) ];
#pragma clang diagnostic pop
    }
    return nil;
}

常用标记

结合上面的 #pragma clang diagnostic进行使用

-Warc-performSelector-leaks   performSelector可能导致内存泄露
-Wundeclared-selector             找不到方法
-Wdeprecated-declarations      废弃的方法
-Wincompatible-pointer-types  指针类型不匹配
-Warc-retain-cycles                  Block的循环引用
-Wunused-variable                   未使用的变量

你可能感兴趣的:(iOS中 #pragma clang diagnostic 的常见用法)