自Xcode 6.3引入,最開始定義的是_nullable和_nonnull,但怕和第三方庫沖突,從Xcode 7就改成了現(xiàn)在看到的_Nullable和_Nonnull
適用范圍
OC對(duì)象和block對(duì)象
_Nullable & _Nonnull
其實(shí)就是寫到星號(hào)后面
@interface AAPLList : NSObject <NSCoding, NSCopying>
// ...
- (AAPLListItem * _Nullable)itemWithName:(NSString * _Nonnull)name;
@property (copy, readonly) NSArray * _Nonnull allItems;
// ...
@end
nullable & nonnull
位置大致是在大括號(hào)的開始
@property (copy, nullable) NSString *name;
@property (copy, readonly, nonnull) NSArray *allItems;
- (nullable AAPLListItem *)itemWithName:(nonnull NSString *)name;
- (NSInteger)indexOfItem:(nonnull AAPLListItem *)item;
Audited Regions
NS_ASSUME_NONNULL_BEGIN
@interface AAPLList : NSObject <NSCoding, NSCopying>
- (nullable AAPLListItem *)itemWithName:(NSString *)name;
- (NSInteger)indexOfItem:(AAPLListItem *)item;
@property (copy, nullable) NSString *name;
@property (copy, readonly) NSArray *allItems;
@end
NS_ASSUME_NONNULL_END
不適用Audited Regions的情況
- typedef定義的類型
- id *類型,需要手動(dòng)指定,比如a non-nullable pointer to a nullable object reference,
_Nullable id * _Nonnull - NSError **,不受其他控制,總是
nullable pointer to nullable NSError object
null_resettable
- only used for property
- setter allow to be set nil
- but getter never produce nil because it have a default value
- example, tintColor of UIView,it has a default value(system color); when set to nil, it reset to system color
@implementation Person
@synthesize greetings = _greetings;
- (void)setGreetings:(NSString *)greetings {
if (greetings) {
_greetings = greetings;
} else {
_greetings = @"hello world";
}
}
- (NSString *)greetings {
if (!_greetings) {
_greetings = @"hello world";
}
return _greetings;
}
@end
Nullability的API在Swift中
- no Nullability -> implicitly unwrapped optionals(String!)
- nullable -> optional(String?)
- nonnull -> non-optional(String)
- null_resettable -> implicitly unwrapped optionals(String!)