objective C 中的 nonnull 是什么?

What is nonnull in objective C?

有人可以详细说明为什么 nonnull 在 iOS 9 中引入吗?

例如,NSArray 方法 + (instancetype)array; 现在是 + (instancetype nonnull)array;

参考: https://developer.apple.com/library/prerelease/ios/releasenotes/General/iOS90APIDiffs/frameworks/Foundation.html

这是 objective-c 级别的功能吗?这对现有应用有何影响?

nonnull 是一个关键字,用于告诉编译器 return 值(或参数,或 属性)永远不会为 nil。这是在 Xcode 的先前版本中引入的,以在 Obj-C 和 Swift 的可选类型之间实现更好的互操作性。

您可以在 the official Swift blog

上了解更多信息

他们确保无论类型是不可空的,它现在都是 nonnull 类型。

与之前的 NSMutableArray addObject 方法一样

- (void)addObject:(ObjectType)anObject  

现在改成了

- (void)addObject:(ObjectType nonnull)anObject

所以这意味着您不能将空对象 (nil) 传递给此方法。同样,在你的情况下

+ (instancetype nonnull) array

方法永远不会returnnil.

参考:https://developer.apple.com/swift/blog/?id=25

引入了

nullable 和 nonnull 以使 Objective C 和 Swift 互操作性更容易。

Objective C 对可选和非可选引用没有任何区别。然后 Swift 编译器无法确定对 Objective C 代码的特定引用是否可选。

nullable 注释与 Swift 中的 optional 相同。 nonnull 注释与 Swift.

中的 non-optional 相同

根据经验,任何简单的指针类型都将被假定为非空(有关更多详细信息,请阅读 the official Swift blog

我还要说,从 Objective C 的角度来看,这个新注释还将提高代码质量。我通常想知道如果将 nil 作为参数传递,应用程序会崩溃吗?例如:

id var;
NSMutableArray *a = [NSMutableArray new];
[a addObject:var];

编译器在这种情况下什么都不说,您的应用程序将在执行时崩溃!现在有了这个新注释,您将在编译时看到警告。我知道这个例子很愚蠢,但在某些情况下,除非您阅读文档,否则您不知道是否需要在调用方法之前检查 属性 是否为 nil。

nonnull 是通知编译器 object/parameters 返回的值永远不会是 nil.

的关键字

In general, you should look at nullable and nonnull roughly the way you currently use assertions or exceptions: violating the contract is a programmer error. In particular, return values are something you control, so you should never return nil for a non-nullable return type unless it is for backwards-compatibility.