Nullable - 表示對象可為null
Nonnull - 表示對象不可為null
而一開始增加此機制時,所提供的關鍵字為__nullable/__nonnull,但是為了處理與第三方套件的衝突,蘋果又將此關鍵字改為_Nullable/_Nonnull,以及沒有底線版本的nonnull/nullable,基本上這三種東西都是同樣的效果,只是放的位置不同而已。
小寫版本的__nullable/__nonnull,應該比較少用了,絕大部分還使用_Nullable/_Nonnull與沒有底線的nonnull/nullable。
那麼有底線跟沒底線的是什麼情景會用到呢,可以參考以下的程式碼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///屬性的修飾 | |
@property (copy, nonnull) NSString *name; | |
///方法回傳值的修飾 | |
- (nonnull NSString *)method; | |
///方法傳入值的修飾 | |
- (void)methodWithString:(nonnull NSString *)string; |
有底線的則是用於Block內傳入的參數或回傳的參數。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///規範Block內的參數為Nonnull | |
- (void)methodWithBlock1:(void(^)(NSString * _Nonnull params))block{ | |
} | |
///沒辦法這樣寫 | |
- (void)methodWithBlock2:(void(^)(nonnull NSString *params))block{ | |
} |
接著你只要在呼叫的時候傳入nil,Xcode就會發出警告。
不過若是每個都要設定成不能Nonnull實在有點麻煩,因此有提供Macro,只要輸入NS_ASSUME_NONNULL_BEGIN與NS_ASSUME_NONNULL_END,在這個區塊內所有的東西就會自動判定為Nonnull,你只需要定義出屬於Nullable的值即可。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NS_ASSUME_NONNULL_BEGIN | |
@interface ViewController () | |
@property (copy) NSString *name; | |
@property (copy, nullable) NSString *nickname; | |
@end | |
NS_ASSUME_NONNULL_END |
接著你可以試著看一下是否有作用。
沒有留言:
張貼留言