Using the GCC __unused attribute with Objective-C

前端 未结 5 1488
野的像风
野的像风 2021-01-04 04:31

Is it possible to use the __unused attribute macro on Objective-C object method parameters? I\'ve tried placing it in various positions around the parameter declaration but

相关标签:
5条回答
  • 2021-01-04 04:58

    A common idiom is to use the following:

    #define UNUSED(x) (void)x
    void SomeFunction(int param1, int param2)
    {
      UNUSED(param2);
      // do stuff with param1
    }

    The UNUSED(param2) statement doesn't generate any object code, eliminates warnings about unused variables, and clearly documents the code as not using the variable.

    0 讨论(0)
  • 2021-01-04 05:04

    I think you can use the #pragma unused to mark arguments as unused. Untested, but you can try something like

    - (NSString *)test:(NSString *)test {
    #pragma unused (test);
      return nil;
    }
    
    0 讨论(0)
  • 2021-01-04 05:12

    Okay, I found the answer... it appears to be a bug with the implementation of Apple's gcc 4.0. Using gcc 4.2 it works as expected and the proper placement is the following:

    -(void)someMethod:(id) __unused someParam;
    

    It's documented in the Objective-C release notes if anyone is interested: http://developer.apple.com/releasenotes/Cocoa/RN-ObjectiveC/index.html#//apple_ref/doc/uid/TP40004309-DontLinkElementID_6

    As a note, your answer will compile, Louis, but as I stated in my question it won't actually do anything or suppress the unused warning issued by the compiler.

    EDIT: I filed a bug report with apple for this rdar://6366051.

    0 讨论(0)
  • 2021-01-04 05:13

    I can compile the following just fine:

    - (NSString *) test:(__unused NSString *)test {
        return nil;
    }
    

    Edit: Actually, that may not be strictly an arch thing:

    Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror
    Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror  -Wunused-parameter
    cc1obj: warnings being treated as errors
    Pusher.m:40: warning: unused parameter ‘test’
    Phoenix-VI:CouchPusher louis$ 
    

    So -Wall does not include not include -Wunused-parameter....

    0 讨论(0)
  • 2021-01-04 05:15

    After fighting with the #pragma for a while, I discovered it's

    + (NSString*) runQuery:(id)query name:(NSString*)name options:(NSDictionary*)options
    {
    #pragma unused(name)
     ...
    
    }
    
    0 讨论(0)
提交回复
热议问题