Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

I am using the following code ...

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

    // super init
    self = [super init];
    if (!self) return nil;

    // set instance variables
    self.mustExist = NO;
    self.reverseCondition = NO;
    self.regularExpression = NO;
    self.variableName = variableName; // generates warning
    self.comparisonValue = comparisonValue; // generates warning

    return self;
}

which generated the following two warnings ...

  • Local declaration of 'variableName' hides instance variable
  • Local declaration of 'comparisonValue' hides instance variable

Is there a common or accepted convention for dealing with these warnings?

I understand that it is simply to inform the user that they should specify an instance when referring to the class member, but its annoying.

like image 724
Nippysaurus Avatar asked Mar 29 '10 22:03

Nippysaurus


3 Answers

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
like image 101
Justin Avatar answered Oct 23 '22 13:10

Justin


Unfortunately, no there's no "good" way to prevent this error. The common pattern is to use a slightly stupid parameter name like

-(id) initWithVariableName:(NSString*)theVariableName 
       withComparisonValue:(NSString*)theComparisonValue {
    self.variableName = theVariableName;
    self.comparisonValue = theComparisonValue;

    return self;
}
like image 31
Barry Wark Avatar answered Oct 23 '22 12:10

Barry Wark


If your method truly is an initialiser, don't forget to do your self = [super init];.

- (id) initWith...
{
    self = [super init];
    if (!self) return nil;

    // do stuff

    return self;
}

I have never personally encountered a situation where self has changed to nil or another value, but it's the Objective-C Initialiser Idiom™.

like image 31
dreamlax Avatar answered Oct 23 '22 13:10

dreamlax