美文网首页
Nullability

Nullability

作者: songgeb | 来源:发表于2019-07-23 10:11 被阅读0次

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

适用范围

OC对象和block对象

_Nullable & _Nonnull

其实就是写到星号后面

@interface AAPLList : NSObject <NSCoding, NSCopying>
// ...
- (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 <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 *类型,需要手动指定,比如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

      本文链接:https://www.haomeiwen.com/subject/xgonlctx.html