有关我们经常会看到德 nonnull和nullable 关键字的使用

来源:互联网 发布:nike篮球鞋淘宝店铺 编辑:程序博客网 时间:2024/06/06 00:38

Nullability Annotations  (可空得标记) ——————-> oc中增加了相应的关键字就是用来和swift混合编程可以兼容

swift 中的?和 !表示一个对象是不是可以选择为空的情况,如view?和view!。
oc中没有区分,所以在混编程的时候,出现无法确定是什么情况。

所以在oc中引入:Nullability Annotations;
这两个新的类型注释:__nullable 和 __nonnull 。
__nullable 表示对象可以是NULL或者nil,
__nunnull 表示对象不应该是空。(如果不遵循这一个规则,编译器将会出现警告)


eg:

@interface TestNullabilityClass ()@property (nonatomic, copy) NSArray * items;- (id)itemWithName:(NSString * <span style="color:#FF0000;">__nonnull</span>)name;@end@implementation TestNullabilityClass- (void)testNullability {    [self itemWithName:nil];    // 编译器警告:Null passed to a callee that requires a non-null argument}- (id)itemWithName:(NSString * <span style="color:#FF0000;">__nonnull</span>)name {    return nil;}@end

在任何可以使用const关键字的地方都可以使用__nullable和__nonnull,不过这两个关键字仅限于使用在指针类型上(也就是类对象)。而在方法的声明中,我们还可以使用不带下划线的nullable和nonnull,

大概:该关键字修饰类型(对象类型),并且在属性和方法在写法有点区别。方法可不带下划线。
- (nullable id)itemWithName:(NSString * nonnull)name@property (nonatomic, copy, nonnull) NSArray * items;@property (nonatomic, copy) NSArray * __nonnull items;(推荐使用 nonnull方式)

Nonnull区域设置(Audited Regions)  ——————> 定义不可以为空得区域方式。批处理思想
可以减轻工作量的方式,就是通过: NS_ASSUME_NONNULL_BEGIN和NS_ASSUME_NONNULL_END 这两个宏来定义
eg:
NS_ASSUME_NONNULL_BEGIN
@interface TestNullabilityClass ()
@property (nonatomic, copy) NSArray * items;
- (id)itemWithName:(nullable NSString *)name;
@end
NS_ASSUME_NONNULL_END
在这两个关键字之间就是nonnull类型的。

注意事项:

1、typedef 定义类型的nullability特性通常依赖于上下文

2、复杂的指针类型(如id *)必须显示去指定是nonnull还是nullable。例如,指定一个指向nullable对象的nonnull指针,可以使用”__nullable id * __nonnull”。
3、我们经常使用的NSError **通常是被假定为一个指向nullable NSError对象的nullable指针。(也就是我们可以通常设置为nil空)

所以这个具有兼容性的作用。

参考连接:
http://www.cocoachina.com/ios/20150601/11989.html








0 0
原创粉丝点击