1. 程式人生 > >ios——備忘__attribute__總結(一)

ios——備忘__attribute__總結(一)

1、__attribute__一般用來設定函式屬性、變數屬性、型別屬性等
格式:__attribute__(xxx)    xxx:即引數
官方例子:NSLog
#define NS_FORMAT_FUNCTION(F,A) __attribute__((format(__NSString__, F, A)))
format屬性可以給被宣告的函式加上類似printf或者scanf的特徵,它可以使編譯器檢查函式宣告和函式實際呼叫引數之間的格式化字串是否匹配。
對於format引數的使用如下
format (archetype, string-index, first-to-check)
archetype指定哪種風格,這裡是__NSString__
string-index指定傳入的第幾個引數是格式化字串
first-to-check指定第一個可變引數所在的索引
2、availability屬性
availability屬性是一個以逗號為分隔的引數列表,以平臺的名稱開始,包含一些放在附加資訊裡的一些里程碑式的宣告。
可以設定廢棄的方法,簡單例子:
- (void)oldMethod:(NSString *)string __attribute__((availability(ios,introduced=2_0,deprecated=7_0,message="用 -newMethod: 這個方法替代 "))){
    NSLog(@"我是舊方法,不要調我");
}


- (void)newMethod:(NSString *)string{
    NSLog(@"我是新方法");
}
//注:如果經常用,建議定義成類似系統的巨集
#define MX_DEPRECATED_IOS(_iosIntro,_iosDep,...)  __attribute__((availability(ios,introduced=_iosIntro,deprecated=_iosDep,message=""__VA_ARGS__)))
上面的例子就變成這樣:
- (void)oldMethod:(NSString *)string  MX_DEPRECATED_IOS(2_0,7_0,"用 -newMethod: 這個方法替代 "){
NSLog(@"我是舊方法,不要調我");
}


- (void)newMethod:(NSString *)string{
    NSLog(@"我是新方法");
}
3、unavailable屬性
告訴編譯器該方法不可用,如果強行呼叫編譯器會提示錯誤。
例子:
#define UNAVAILABLE_ATTRIBUTE __attribute__((unavailable))
#define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE
4、NSObject屬性
例子:
@property (nonatomic,strong) __attribute__((NSObject)) CFDictionaryRef myDictionary;
CFDictionaryRef屬於CoreFoundation框架的,也就是非OC物件,加上attribute((NSObject))後,myDictionary的記憶體管理會被當做OC物件來對待.
另外一個例子:
typedef __attribute__((NSObject)) CGGradientRef GradientObject;
@property (nonatomic, strong) GradientObject storedGradient;
CGGradientRef屬於Core Graphics框架,非OC物件,首先將CGGradientRef起別名為GradientObject,並使其記憶體管理會被當做OC物件來對待.