今天看博客看到了sunnyxx大神介绍了关于attribute的一个黑魔法,并且我在ibirme大神的源代码里面也看到他用过这个属性,我就系统的学习了一下,记录一下常用的方法。
这个format有3个参数。
int my(NSString *str,NSString *str1,NSArray*str2,...) __attribute__((format(__NSString__,2,4)));
如果你把第二个参数改成别的类型,或者加一个参数,使可变参数变成了第五个,这都是不行的。
这个参数可以无数多个
int my(NSString *str,NSString *str1,NSArray*str2,...) __attribute__((nonnull(1,3)));
此方法没有参数,表示这个函数没有返回值也不能有返回值。
#define onExit\ __strong void(^block)(void) __attribute__((cleanup(blockCleanUp), unused)) = ^一个巧妙的用法就是像上面一样定义一个宏,然后
{ onExit { NSLog(@"yo"); }; }在这个onExit中的代码就会在最后执行,这段是在sunnyxx的博客中看到的,应用于reactive cocoa。
static __inline__ __attribute__((always_inline))
将这段代码定义成一个宏,然在函数的前边就能直接强制内联,如果是频繁调用的函数,这样可以提高一定的效率。
在系统的base.h文件中,苹果为很多属性定义了宏,有下面这些
#define OS_NORETURN __attribute__((__noreturn__))
#define OS_NOTHROW __attribute__((__nothrow__))
#define OS_NONNULL1 __attribute__((__nonnull__(1)))
#define OS_NONNULL2 __attribute__((__nonnull__(2)))
#define OS_NONNULL3 __attribute__((__nonnull__(3)))
#define OS_NONNULL4 __attribute__((__nonnull__(4)))
#define OS_NONNULL5 __attribute__((__nonnull__(5)))
#define OS_NONNULL6 __attribute__((__nonnull__(6)))
#define OS_NONNULL7 __attribute__((__nonnull__(7)))
#define OS_NONNULL8 __attribute__((__nonnull__(8)))
#define OS_NONNULL9 __attribute__((__nonnull__(9)))
#define OS_NONNULL10 __attribute__((__nonnull__(10)))
#define OS_NONNULL11 __attribute__((__nonnull__(11)))
#define OS_NONNULL12 __attribute__((__nonnull__(12)))
#define OS_NONNULL13 __attribute__((__nonnull__(13)))
#define OS_NONNULL14 __attribute__((__nonnull__(14)))
#define OS_NONNULL15 __attribute__((__nonnull__(15)))
#define OS_NONNULL_ALL __attribute__((__nonnull__))
#define OS_SENTINEL __attribute__((__sentinel__))
#define OS_PURE __attribute__((__pure__))
#define OS_CONST __attribute__((__const__))
#define OS_WARN_RESULT __attribute__((__warn_unused_result__))
#define OS_MALLOC __attribute__((__malloc__))
#define OS_USED __attribute__((__used__))
#define OS_UNUSED __attribute__((__unused__))
#define OS_WEAK __attribute__((__weak__))
#define OS_WEAK_IMPORT __attribute__((__weak_import__))
#define OS_NOINLINE __attribute__((__noinline__))
#define OS_ALWAYS_INLINE __attribute__((__always_inline__))
#define OS_TRANSPARENT_UNION __attribute__((__transparent_union__))
#define OS_ALIGNED(n) __attribute__((__aligned__((n))))
#define OS_FORMAT_PRINTF(x,y) __attribute__((__format__(printf,x,y)))
#define OS_EXPORT extern __attribute__((__visibility__("default")))
#define OS_INLINE static __inline__
#define OS_EXPECT(x, v) __builtin_expect((x), (v))