I run into a fairly common scenario in Objective-C where I pass in a variable to an init method and then want to assign it to an instance variable of the same name. However I have not found a way to scope the variables to clarify which is the value from the message argument and which is the instance variable.
Say I have some class such as the following:
@interface MyObject
{
NSString *value;
}
- (id)initWithValue:(NSString *)value;
@end
In my implementation I want my init method to look something like this:
- (id)initWithValue:(NSString *)value
{
self = [super init];
if(self) {
self.value = value; // This will not work with instance variables
}
}
I know of three solutions:
- Create a property, which allows calling
self.value
- Rename my instance variable, such as
_value
- Rename my init argument variable, such as
initValue
orargValue
I am not pleased with any of these solutions. Adding a property either makes the property publicly available on the interface or, if I use an extension, hides it from inheritors. I also do not like having different names for the variables or using an underscore, which perhaps comes from developing in other languages such as Java and C#.
Is there a way to disambiguate instance variables from message arguments? If not, is there a coding guideline in Cocoa for how to solve this problem? I like following style guidelines when appropriate.
Update
After thinking about how to do this in C, I came up with the solution of self->value
. This works, but it produces a compiler warning that the Local declaration of 'value' hides instance variable. So this is not a satisfactory solution either since I have a zero-warning goal.