Objective-C convention to prevent “local declaration hides instance variable” warning

前端 未结 9 1369
滥情空心
滥情空心 2020-12-08 04:50

I am using the following code ...

-(id) initWithVariableName:(NSString*)variableName withComparisonValue:(NSString*)comparisonValue {

    // super init
             


        
相关标签:
9条回答
  • 2020-12-08 05:38

    I see this is a fairly old question with a accepted answer but I have a better solution and its code convention.

    The convention states that you prefix private variables with a underscore (_varName) and public (like properties) with just the name.

    With this you just can call the same variable name in your functions.

    Example:

    ExampleClass.h

    @interface ExampleClass : NSObject
    {
        NSString *_varName; //this is not required if you create a property
    }
    
    @property (nonatomic, retain) NSString *varName;
    
    - (void)someMethodWithVarName:(NSString *)varName;
    
    @end
    

    ExampleClass.m

    #import "ExampleClass.h"
    
    @implementation ExampleClass
    
    @synthesize varName = _varName; //if you don't declare the _varName in the header file, Objective-C does it for you.
    
    - (id)init
    {
        self = [super init];
        if (self) {
            // Initialization code here.
        }
    
        return self;
    }
    
    - (void)someMethodWithVarName:(NSString *)varName
    {
        _varName = varName; //just for example purpose
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-08 05:40

    This is not a problem at all in the modern Objective-C. In the modern Objective-C, properties are automatically synthesized and their corresponding instance variables get a _ prefix.

    So, with auto-synthesis your properties would create instance variables _variableName and _comparisonValue. No shadowing occurs in this case.

    More info in this blog post


    If you absolutely need to manually synthesize your properties, rename the sinthesized ivar like this

    @synthesize variableName = _variableName;
    

    In general case, rename your method arguments.

    0 讨论(0)
  • 2020-12-08 05:41

    You should generally prefix instance variables with something like an underscore (e.g. _variableName) to avoid compiler warnings like this.

    Otherwise just slightly change the names in your method signature, there is no hard defined naming convention.

    0 讨论(0)
提交回复
热议问题