What is nonnull in objective C?

后端 未结 4 481
一向
一向 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: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.

提交回复
热议问题