Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a 'nonnil' attribute for clang?

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?

like image 944
griotspeak Avatar asked Oct 04 '13 16:10

griotspeak


1 Answers

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;
like image 104
Dave DeLong Avatar answered Oct 14 '22 08:10

Dave DeLong