Search code examples
objective-chidden-variables

Parameters hide instance variables in Objective-C


Is there a way to give a parameter to a method the same name as an instance variable in Objective-C without hiding that variable?

For instance,

- (void)doSomething:(id)object
{
    self.object = object;
}

The code above gives the warning "local declaration of 'object' hides instance variable."

The obvious solution is to name the parameter arguments differently, but I find it annoying having to choose a name like "anObject" instead of "object".


Solution

  • You can use dot notation to access properties (as you do in the example), but instance variables have only one access path, so the only solution if you want to access both an instance variable and a local variable is to give them different names.

    Formally speaking, this is related to the restrictions on alpha conversion in lambda calculus, specifically that a bound variable should remain bound and a free variable remain free.

    If you don't like the "an" prefix for locals, you can use the "_" prefix convention for instance variables, as they're also effectively protected variables.

    @interface AClass {
        id _object;
    }
    @property (retain) id object;
    @end
    
    @implementation AClass
    @synthesize object = _object;
    
    - (void)doSomething:(id)object
    {
        [_object befriend:object];
    }
    ...
    

    Of course, "_" reads as "my", so it may be just as distasteful as "a"/"an" before parameters. Renaming is the best solution as instance and local variables have different roles, and their names should reflect this.