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".
Instance variable hiding refers to a state when instance variables of the same name are present in superclass and subclass. Now if we try to access using subclass object then instance variable of subclass hides instance variable of superclass irrespective of its return types.
Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.
Variable hiding happens when a variable declared in the child class has the same name as the variable declared in the parent class. The hidden variable of the parent class can be accessed using the super keyword.
You might be able to do something like self->object = object
, but the Objective-C convention (derived from Smalltalk) is to prefix parameters with "a" or "an" if the parameter has the same name as an instance variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With