iOS 中常见的__attribute__

1.__attribute((nonnull()))

场景:nonnull(不为空参数的序号从1开始)

- (void)test:(NSString *)str str2:(NSString *)str2 __attribute((nonnull(1,2))) {
    //这里想传进来的str 和 str2 不为nil
}
- (void)test:(NSString *)str str2:(NSString *)str2 __attribute((nonnull(1)))  {
    //这里想传进来的str  不为nil
}

2.__attribute__((constructor))

使用这个可以保证该方法在main函数之前被调用

__attribute__((constructor)) void test1() {
    NSLog(@"test1-----");
}
DE413677-ADED-4854-A615-FE195BB77F29.png

3.__attribute__((cleanup()))

用于修饰一个变量,在它的作用域结束时可以自动执行一个指定的方法

static void stringCleanUp(__strong NSString  ** string){
    NSLog(@"%@", * string);
}
- (void)viewDidLoad {
    [super viewDidLoad];

    __strong NSString *string __attribute__((cleanup(stringCleanUp))) = @"test";
    
    NSLog(@"viewDidLoad
![D8E0DD3B-D123-4430-B6BF-5C4CA869FEFF.png](http://upload-images.jianshu.io/upload_images/3279997-7595e67110457a95.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)");
}

当运行到这个作用域结束时对应的方法会调用,所有viewDidLoad的打印顺序是先打印“viewDidLoad------”再打印"test"

4. NS_REQUIRES_SUPER

场景:
有时我们设计接口供子类继承的时候需要子类在实现的时候要调用super的实现。

#import 

@interface Demo36obj : NSObject

- (void)test NS_REQUIRES_SUPER ;

@end

当继承Demo36obj的子类Demo36objSub实现test方法的时候,你会发现此时会有黄色的警告

@implementation Demo36objSub

- (void)test { 
}
@end

通过这个修饰的方法我们可以约束子类的行为

当然如果你确定不使用父类的实现又想消除警告 ,你也可以通过下面的方式这个来消除警告

#import "Demo36objSub.h"

@implementation Demo36objSub

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-missing-super-calls"
- (void)test {
    
}
@end
#pragma clang diagnostic pop

5. __attribute__((unused))

可以忽略一些没有使用的变量造成的警告

- (void)testMyFastIterator {

     NSString *testString  = @"test";

}

会报下面的警告

可以使用__attribute__((unused))忽略

NSString *testString __attribute__((unused))  = @"test";

References:
http://nshipster.com/attribute/
https://clang.llvm.org/docs/AttributeReference.html

6. static __attribute__((always_inline))

static __attribute__((always_inline)) 将函数标记为内联函数,一般会这种static inline写法 ,前面的写法当你不开启optimization也会内联。

你可能感兴趣的:(iOS 中常见的__attribute__)