一丶介绍
attribute 是 GNU C 的一大特色。
二丶使用
1.函数属性
函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。attribute机制也很容易同非GNU应用程序做到兼容之功效。
语法格式为:
format (archetype, string-index, first-to-check)
具体使用格式如下:
__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))
m:第几个参数为格式化字符串(format string);
n:参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几
实例:

去掉attribute((format(printf,1,2))),则会正常编译。
扩展:
顺便看下OC里的NSLog定义:
NSObjCRuntime.h


2.变量属性
2.1__attribute__((cleanup(...))),用于修饰一个变量,在它的作用域结束时可以自动执行一个指定的方法
实例1:

打印顺序:

注意:cleanup是先于这个对象的dealloc调用的
示例2:
Block属性的使用
摘自:http://blog.sunnyxx.com/2014/09/15/objc-attribute-cleanup/

2.2__attribute__((deprecated("")) 弃用
在OC中,可以使用 DEPRECATED_MSG_ATTRIBUTE(s) 这个宏
使用:

三丶参考文章:
http://blog.csdn.net/juana1/article/details/6849120
http://blog.sunnyxx.com/2014/09/15/objc-attribute-cleanup/
网友评论