Attributes in Clang

Clang官方文档:Clang documentation

  • objc_runtime_name
    用于 @interface 或 @protocol,指定类或协议编译后的名字
    attribute((objc_runtime_name("MyLocalName")))
    @interface Message
    @end
    // (lldb) po [self class]
    // MyLocalName

  • objc_requires_super
    指定子类覆写该方法时需要调用父类方法

The attribute to designate that a method requires a “call to super
” in the overriding method in the subclass.

  - (void)foo __attribute__((objc_requires_super));
  • objc_subclassing_restricted
    禁止继承
    attribute((objc_subclassing_restricted))
    @interface A : NSObject
    @end

    @interface B : A //  Cannot subclass a class with objc_subclassing_restricted attribute
    @end
    
  • objc_runtime_visible
    禁止继承和category

This attribute specifies that the Objective-C class to which it applies is visible to the Objective-C runtime but not to the linker. Classes annotated with this attribute cannot be subclassed and cannot have categories defined for them.

  • constructor / destructor
    添加这两个属性的函数会在分别在可执行文件(或 shared library)load 和 unload 时被调用,即main()函数调用前和main()函数return后执行,执行顺序:+load -> constructor -> main -> destructor

    __attribute__((constructor))
    static void beforeMain(void) {
        NSLog(@"%s", __func__);  // beforeMain 
    }
    
    __attribute__((destructor))
    static void afterMain(void) {
        NSLog(@"%s", __func__);  // afterMain (main函数return后执行)
    }
    

    constructor可控制优先级,如__attribute__((constructor(101))),数字越小优先级越高,1-100为系统保留。

  • cleanup
    声明的变量作用域结束后调用指定函数

    {
        __strong XXObject *obj __attribute__((cleanup(cleanuptest))) = [[XXObject alloc]init];
        [obj test];
    }
    NSLog(@"end");
    
    static void cleanuptest(__strong XXObject **obj)
    {
        XXObject *obj_t = *obj;
        NSLog(@"%s", __func__);
    }
    
    // 2016-05-25 15:38:08.350 Test[2559:159531] cleanuptest
    // 2016-05-25 15:38:08.350 Test[2559:159531] -[XXObject dealloc]
    // 2016-05-25 15:38:08.350 Test[2559:159531] end

你可能感兴趣的:(Attributes in Clang)