蘋果在 Xcode 6.3 引入了一個 Objective-C 的新特性:Nullability Annotations,這一新特性的核心是兩個新的類型修飾:__nullable和__nonnull。從字面上我們可知,__nullable表示對象可以是 NULL 或 nil,而__nonnull表示對象不應該為空。當我們不遵循這一規則時,編譯器就會給出警告。在 Xcode 7 中,為了避免與第三方庫潛在的沖突,蘋果把__nonnull/__nullable改成_Nonnull/_Nullable。再加上蘋果同樣支持了沒有下劃線的寫法nonnull/nullable,于是就造成現在有三種寫法這樣混亂的局面。但是這三種寫法本質上都是互通的,只是放的位置不同,舉例如下:
方法返回值修飾:
- (nullableNSString*)method;- (NSString* __nullable)method;- (NSString* _Nullable)method;
聲明屬性的修飾:
@property(nonatomic,copy,nullable)NSString*aString;
@property(nonatomic,copy)NSString* __nullableaString;
@property(nonatomic,copy)NSString* _Nullable aString;
方法參數修飾:
- (void)methodWithString:(nullableNSString*)aString;- (void)methodWithString:(NSString* _Nullable)aString;- (void)methodWithString:(NSString* __nullable)aString;
而對于雙指針類型對象、Block 的返回值、Block 的參數等,這時候就不能用nonnull/nullable修飾,只能用帶下劃線的__nonnull/__nullable或者_Nonnull/_Nullable:
- (void)methodWithError:(NSError* _Nullable * _Nullable)error- (void)methodWithError:(NSError* __nullable* __null_unspecified)error;// 以及其他的組合方式
- (void)methodWithBlock:(nullablevoid(^)())block;// 注意上面的 nullable 用于修飾方法傳入的參數 Block 可以為空,而不是修飾 Block 返回值;- (void)methodWithBlock:(void(^ _Nullable)())block;- (void)methodWithBlock:(void(^ __nullable)())block;
- (void)methodWithBlock:(nullableid__nonnull(^)(id__nullableparams))block;
// 注意上面的 nullable 用于修飾方法傳入的參數 Block可以為空,而 __nonnull 用于修飾 Block 返回值 id 不能為空;
- (void)methodWithBlock:(id__nonnull(^ __nullable)(id__nullableparams))block;
- (void)methodWithBlock:(id_Nonnull (^ _Nullable)(id_Nullable params))block;
// the method accepts a nullable blockthat returns a nonnullvalue
// therearesomemore combinations here, yougetthe idea
以上基本上羅列了絕大部分的使用場景,但看完我們還是一臉懵逼啊,仍然不清楚什么時候應該用哪個修飾符!
在看了原生 iOS SDK 里 Foundation 和 UIKit 的頭文件以及蘋果的博文《Nullability and Objective-C》,我們總結如下使用規范:
對于屬性、方法返回值、方法參數的修飾,使用:nonnull/nullable;
對于 C 函數的參數、Block 的參數、Block 返回值的修飾,使用:_Nonnull/_Nullable,建議棄用__nonnull/__nullable。
如果需要每個屬性或每個方法都去指定nonnull和nullable,將是一件非常繁瑣的事。蘋果為了減輕我們的工作量,專門提供了兩個宏:NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END。在這兩個宏之間的代碼,所有簡單指針對象都被假定為nonnull,因此我們只需要去指定那些nullable指針對象即可。如下代碼所示:
NS_ASSUME_NONNULL_BEGIN
@interfacemyClass()
@property(nonatomic,copy)NSString*aString;
-(id)methodWithString:(nullableNSString*)str;
@end
NS_ASSUME_NONNULL_END
在上面的代碼中,aString屬性默認是nonnull的,methodWithString:方法的返回值也是nonnull,而方法的參數str被顯式指定為nullable。
不過,為了安全起見,蘋果還制定了以下幾條規則:
通過typedef定義的類型的nullability特性通常依賴于上下文,即使是在 Audited Regions 中,也不能假定它為nonnull;
對于復雜的指針類型(如id *)必須顯式去指定是nonnull還是nullable。例如,指定一個指向nullable對象的nonnull指針,可以使用__nullable id * __nonnull;
我們經常使用的NSError **通常是被假定為一個指向nullableNSError 對象的nullable指針。