Search code examples
objective-cxcode8

Ignoring return value of function declared with "warn_unused_result" attribute


We start having this warning on all the becomeFirstResponder function call in our Objective-C code.

Ignoring return value of function declared with "warn_unused_result" attribute

[self.phoneNumberField becomeFirstResponder]; // warning here!!!

What's the best way to suppress this warning here?


Edit: I also tried this,

BOOL ignore = [self.emailField becomeFirstResponder]; 

But with that, Xcode has warning about the variable ignore is not used :(


I also tried this,

BOOL ignore = [self.phoneNumberField becomeFirstResponder];
if (ignore) {

}

The warnings is gone in this case. But I don't think I can even past my own code review. It is too ugly!


Solution

  • It should work to cast the expression to a void expression.

    (void)[self.emailField becomeFirstResponder]; 
    

    (Even I cannot reproduce the warning. However, this might depend on the warning flags.)

    To your edit:

    BOOL ignore = [self.emailField becomeFirstResponder]; 
    

    Likely

    BOOL ignore = [self.emailField becomeFirstResponder]; 
    ignore = ignore;
    // or
    (void)ignore;
    

    should remove the warning. (It does with my flags.) However, this an ugly hack, too.

    BTW: There is a reason for the attribute. Maybe you should recheck, whether it is a good idea, not to test for the return value.