Nullability

自Xcode 6.3引入,最开始定义的是_nullable_nonnull,但怕和第三方库冲突,从Xcode 7就改成了现在看到的_Nullable_Nonnull

适用范围

OC对象和block对象

_Nullable & _Nonnull

其实就是写到星号后面

@interface AAPLList : NSObject 
// ...
- (AAPLListItem * _Nullable)itemWithName:(NSString * _Nonnull)name;
@property (copy, readonly) NSArray * _Nonnull allItems;
// ...
@end

nullable & nonnull

位置大致是在大括号的开始

@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 
- (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 *类型,需要手动指定,比如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!)

参考

  • Nullability and Objective-C
  • esignating Nullability in Objective-C APIs
  • nonnull, nullable, and null_resettable for Objective-C and Swift

你可能感兴趣的:(Nullability)