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

前端 未结 9 1425
滥情空心
滥情空心 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
    

提交回复
热议问题