What is nonnull in objective C?

后端 未结 4 468
一向
一向 2021-02-05 09:49

Can someone elaborate why is nonnull introduced in iOS 9 ?

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

相关标签:
4条回答
  • 2021-02-05 10:32

    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

    0 讨论(0)
  • 2021-02-05 10:43

    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.

    0 讨论(0)
  • 2021-02-05 10:45

    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

    0 讨论(0)
  • 2021-02-05 10:56

    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.

    0 讨论(0)
提交回复
热议问题