- 关键字:
nullable
,作用:表示此值可以为空。 nullable
只能修饰对象,不能修饰基本数据类型。- 书写方式示例,如下:
// 方式一:
@property (nonatomic, strong, nullable) NSString* nameOne;
// 方式二:
@property (nonatomic, strong) NSString* _Nullable nameTwo;
// 方式三:
@property (nonatomic, strong) NSString* __nullable nameThree;
- 关键字:
nonnull
,作用:表示此值非空 nonnull
只能修饰对象,不能修饰基本数据类型。- 书写方式示例,如下:
// 方式一:
@property (nonatomic, strong, nonnull) NSString* genderOne;
// 方式二:
@property (nonatomic, strong) NSString* _Nonnull genderTwo;
// 方式三:
@property (nonatomic, strong) NSString* __nonnull genderThree;
- 也可以在定义方法的时候使用:
// 返回值和参数都不能为空
// 方式一:
- (nonnull NSString *)functionNameOne:(nonnull NSString *)name;
// 方式二:
- (NSString* _Nonnull)functionNameTwo:(NSString * _Nonnull)name;
如果仅仅是某一个属性值不能为空,可以单独对其使用
nonnull
关键字。如果有较多的属性值和方法中的值不能为空,可以使用
NS_ASSUME_NONNULL_BEGIN
和NS_ASSUME_NONNULL_END
;在这两个之间的对象属性和方法默认都是nonnull
。在
UIView
头文件内,我们可以看到上述宏的使用。
- 关键字:
null_resettable
,作用:get
不能返回空,set
可以为空 - 注意:如果使用
null_resettable
,必须重写get
方法或者set
方法,处理传递的值为空的情况。 - 书写方式示例,如下:
@property (nonatomic, strong, null_resettable) NSString* name;
// set
- (void)setName:(NSString *)name{
if (name == nil) {
name = @"wangsk";
}
_name = name;
}
// get
- (NSString *)name{
if (_name == nil) {
_name = @"wangsk";
}
return _name;
}
- 关键字:
_Null_unspecified
,作用:不确定此值是否为空 - 书写方式示例,如下:
// 方式一:
@property (nonatomic, strong) NSString* _Null_unspecified nameOne;
// 方式二:
@property (nonatomic, strong) NSString* __null_unspecified nameTwo;