nonnull
works for C functions but not obj-c methods. To be clear, I am suggesting this
- (void)doSomethingWithRequiredString:(NSString * __attribute((nonnil)))requiredString
bar:(NSString *)optionalString);
or (more like nonnull)
- (void)doSomethingWithRequiredString:(NSString *)requiredString
bar:(NSString *)optionalString)
__attribute((nonnil(0)));
I have puzzled over whether or not there is a good technical reason. I understand that clang could only really use the attribute for a compile time check or static analysis, but that seems orthogonal. Is there some strong reason not to have this?
You totally can. The only thing you're doing wrong is thinking that method parameters are 0-indexed, when in fact they're 1-indexed (oh, and it's nonnull
, not nonnil
):
- (void)doSomethingWithRequiredString:(NSString *)requiredString
bar:(NSString *)optionalString
__attribute((nonnull(1)));
Now when you try to use that:
id thing = ...;
[thing doSomethingWithRequiredString:nil bar:@"42"];
Xcode will warn you with a by saying "Null passed to a callee which requires a non-null argument".
Also, if you leave out the "(1)" portion of the __attribute, it's assumed that the non-nil requirement applies to all parameters.
Clang recognizes the GCC attributes, and GCC's definition of the nonnull
attribute is here: http://gcc.gnu.org/onlinedocs/gcc-4.0.0/gcc/Function-Attributes.html#index-g_t_0040code_007bnonnull_007d-function-attribute-1733
Update: As of Xcode 6.3 a cleaner syntax is supported.
In properties and methods the keywords are nullable
, nonnull
and null_unspecified
.
So your method signature would become this:
- (void)doSomethingWithRequiredString:(nonnull NSString *)requiredString
bar:(nullable NSString *)optionalString;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With