iOS 9 新增了一組空值標註關鍵字,用來修飾屬性、方法參數與返回值。它們的好處在於:一方面迎合 Swift 的 Optional 類型,另一方面能提高開發規範、減少團隊溝通成本。
注意:這些關鍵字只能修飾對象類型,不能修飾基本數據類型。
@property (nonatomic, strong, nullable) NSString *name; @property (nonatomic, strong) NSString *_Nullable name; @property (nonatomic, strong) NSString *__nullable name;
@property (nonatomic, strong, nonnull) NSString *icon; @property (nonatomic, strong) NSString * _Nonnull icon; @property (nonatomic, strong) NSString * __nonnull icon;
在 NS_ASSUME_NONNULL_BEGIN 與 NS_ASSUME_NONNULL_END 之間定義的所有對象屬性和方法,默認都是 nonnull。
@property (nonatomic, strong, null_resettable) NSString *name; // 注意:使用null_resettable必須重寫get方法,處理返回值為空的情況
@property (nonatomic, strong) NSString *_Null_unspecified name; @property (nonatomic, strong) NSString *__null_unspecified name;