Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the meaning of this: _Pragma("clang assume_nonnull begin")

After I read some Objective-c code, I found this sentence is above the interface, can someone tell me the meaning, or it is thankful to give some tutorials about clang, thanks a lot

like image 538
whitekevin Avatar asked Jan 05 '23 07:01

whitekevin


1 Answers

In newer versions of the Objective-C compiler (clang), parameters, return values, variables, and properties can be defined as allowing or not null values.

This is typically done for each pointer in a declaration by adding the _Nullable or _Nonnull attribute:

int fetch(int * _Nonnull ptr);

This means you can't pass nil to the fetch function.

There are times where you might want every (or most) pointer to be non-null, for example. It gets tedious having to add _Nonnull to every pointer in the header file. To make this easier, you can add the pragma at the start of the file and the corresponding end pragma at the end. This will default all pointers to being non-null. If you then need one or two to be nullable, you can add _Nullable to just those pointers.

In iOS and macOS you can use NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END instead of _Pragma("clang assume_nonnull begin") and _Pragma("clang assume_nonnull end").

Of course there are also "nullable" versions too if you want everything to default to nullable instead of non-null.

You can read more about clang and the nullability attributes at https://clang.llvm.org/docs/AttributeReference.html#nullability-attributes

like image 195
rmaddy Avatar answered Feb 12 '23 00:02

rmaddy