看到了sunny大神最新的博客,感觉很实用,这里就挑选几个我认为更实用的转载过来。因为没有提前征得sunny同意,如果sunny大神认为不合适的话,烦请通知我一声,谢谢。
Clang Attributes 是 Clang 提供的一种源码注解,方便开发者向编译器表达某种要求,参与控制如 Static Analyzer、Name Mangling、Code Generation 等过程,一般以 attribute(xxx)
的形式出现在代码中;为方便使用,一些常用属性也被 Cocoa 定义成宏,比如在系统头文件中经常出现的NS_CLASS_AVAILABLE_IOS(9_0)
就是 attribute(availability(...))
这个属性的简单写法。
objc_subclassing_restricted
使用这个属性可以定义一个 Final Class,也就是说,一个不可被继承的类。假设我们有个名叫Eunuch(太监) 的类,但并不希望有人可以继承自它:
@interface Eunuch : NSObject
@end
@interface Child : Eunuch // 太监不能够有孩砸
@end
只要在 @interface 前面加上 objc_subclassing_restricted
这个属性即可:
__attribute__((objc_subclassing_restricted))
@interface Eunuch : NSObject
@end
@interface Child : Eunuch // <--- Compile Error
@end
objc_requires_super
#define NS_REQUIRES_SUPER __attribute__((objc_requires_super))
标志子类继承这个方法时必须调用 super:
@interface Father : NSObject
- (void)hailHydra __attribute__((objc_requires_super));
@end
@implementation Father
- (void)hailHydra {
NSLog(@"hail hydra!");
}@end
@interface Son : Father
@end
@implementation Son
- (void)hailHydra {
} // <--- Warning missing [super hailHydra]
@end
objc_boxable
Objective-C 中的 @(...)语法糖可以将基本数据类型 bo成 NSNumber
对象,假如想 box 一个struct类型或是 union类型成 NSValue对象可以使用这个属性:
typedef struct __attribute__((objc_boxable)) {
CGFloat x, y, width, height;
} XXRect;
这样一来,XXRect就具备被 box 的能力:
CGRect rect1 = {1, 2, 3, 4};
NSValue *value1 = @(rect1); // <--- Compile ErrorXXRect
rect2 = {1, 2, 3, 4};
NSValue *value2 = @(rect2); // √
constructor / destructor
顾名思义,构造器和析构器,加上这两个属性的函数会在分别在可执行文件(或 shared library)load和 unload 时被调用,可以理解为在 main()函数调用前和 return 后执行:
__attribute__((constructor))
static void beforeMain(void) {
NSLog(@"beforeMain");
}
__attribute__((destructor))
static void afterMain(void) {
NSLog(@"afterMain");
}
int main(int argc, const char * argv[]) {
NSLog(@"main");
return 0;
}
// Console:
// "beforeMain" -> "main" -> "afterMain"
constructor 和 +load都是在 main 函数执行前调用,但 +load比 constructor 更加早一丢丢,因为 dyld(动态链接器,程序的最初起点)在加载 image(可以理解成 Mach-O 文件)时会先通知 objc runtime去加载其中所有的类,每加载一个类时,它的 +load随之调用,全部加载完成后,dyld 才会调用这个 image 中所有的 constructor 方法。
所以 constructor 是一个干坏事的绝佳时机:
- 所有 Class 都已经加载完成
- main 函数还未执行
- 无需像 +load 还得挂载在一个 Class 中
enable_if
这个属性只能用在 C 函数上,可以用来实现参数的静态检查:
static void printValidAge(int age)
__attribute__((enable_if(age > 0 && age < 120, "你丫火星人?"))) {
printf("%d", age);
}
它表示调用这个函数时必须满足 age > 0 && age < 120才被允许,于是乎:
printValidAge(26); // √
printValidAge(150); // <--- Compile Error
printValidAge(-1); // <--- Compile Error
文章转载自sunny大神的博客。http://blog.sunnyxx.com/2016/05/14/clang-attributes/