Sarreph
Sarreph

Reputation: 2015

Is it OK to have a method's variable with the same name as a declared property?

I understand this is probably bad practice, but I was just curious as to whether or not this has any negative side-effects, in Objective-C (trying to learn as much as I can):

@interface MyClass ()

// Declare a string called 'foo'

@property (nonatomic, strong) NSString *foo

@end

@implementation MyClass 

...

- (void)modifyFoo {

    // Create a local variable with the same name as a property

    NSString *foo = @"Hello!" // No compiler warnings?

    self.foo = foo; // <---- Is this OK?

}

This will not throw up a warning in the compiler, and sure enough, my code works as normal. If there are zero negative side-effects, does the type of property, e.g. weak/strong/assign, etc, have an influence on whether or not this is OK?

Note: I am aware that this will not work when the property is synthesised.

Upvotes: 0

Views: 78

Answers (2)

user529758
user529758

Reputation:

Firstly:

this will not work when the property is synthesised.

Huh? Why not?


Actually, it's "OK" in the sense that it works. Actually, there's no ambiguity when you use the self keyword and the dot notation to access your property. If, however, you had an instance variable with the same name as your local variable, then the object with a narrower scope (the local variable in this case) hides the one with a wider scope (the ivar). And that may be undesirable. As far as I know, it even results in a compiler warning. Furthermore, it's hard to get it wrong and decreases overall code readability, so don't do this if you have that identically named instance variable.

If I recall correctly, recent versions of the clang/LLVM toolchain automatically synthesize properties for you, and the name of the backing ivar for a property is preceded by a leading underscore, so this should not be a problem.

Upvotes: 2

Wain
Wain

Reputation: 119031

This is fine and is my personally preferred approach. The reason no compiler warning is generated is that the instance variable is actually named _foo. This is done by the auto-synthesise added by the compiler (it generates @synthesize foo = _foo for you). Maintaining naming consistency aids clarity.

The main potential side effect is that you inadvertently add / fail to add self. and end up trying to message nil.

Upvotes: 4

Related Questions