What is nonnull in objective C?

2020-05-25 18:36发布

问题:

Can someone elaborate why is nonnull introduced in iOS 9 ?

For example, the NSArray method + (instancetype)array; is now + (instancetype nonnull)array;

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

Is this an objective-c level feature, and how would this affect the existing apps ?

回答1:

They have made sure that wherever the type is not-nullable it is now a nonnull type.

Like earlier NSMutableArray addObject method was

- (void)addObject:(ObjectType)anObject  

and now it has been changed to

- (void)addObject:(ObjectType nonnull)anObject

So it means you cannot pass a null object (nil) to this method. Same way, in your case

+ (instancetype nonnull) array

method will never return nil.

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



回答2:

nonnull is a keyword to tell the compiler that the return value (or parameter, or property) will never be nil. This was introduced in a previous version of Xcode to enable better inter operability between Obj-C and Swift's optional types.

You can learn more about it on the official Swift blog



回答3:

nonnull is keyword which notify compiler that the value returned by object/parameters will never be 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.



回答4:

nullable and nonnull has been introduced to make Objective C and Swift interoperability easier.

Objective C doesn't make any difference between optional and non-optional references. Then Swift compiler cannot be sure if a particular reference to Objective C code is optional or not.

nullable annotation is the same than optional in Swift. nonnull annotation is the same than non-optional in Swift.

The rule of thumb is any simple pointer type will be assumed to be nonnull (for more details read the official Swift blog)

I would also say that this new annotation will also improve code quality from Objective C point of view. I usually wonder would the app crash if a pass nil as parameter? For example:

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

Compiler doesn't say anything in this case and your application will crash in execution time! Now with this new annotation you will see a warning in compilation time. I know this example is stupid, but there are some cases that you don't know if you need to check whether or not a property is nil before calling a method unless you read the documentation.