Luca Davanzo
Luca Davanzo

Reputation: 21528

Objective-c: Instance variable and property with same name

I found this code and I was dumbfounded:

@interface MyNode : NSObject {
    Node *node;
}

@property(nonatomic,strong) Node *node;

@end

What is the behaviour of this code?
I think that property declaration of "node" ovveride an shadow previous declaration, isn't it?

Upvotes: 0

Views: 546

Answers (2)

OpenUserX03
OpenUserX03

Reputation: 1458

The behavior of your code is that you declared a property, and an instance variable. The @property(nonatomic,strong) Node *node; will have an instance variable _node auto synthesized by the compiler (this was introduced in Xcode 4.4).

Therefore, your class now has a node and _node instance variable.

Perhaps if you read the documentation then you won't be so dumbfounded when you come across programming language constructs!

Upvotes: 1

gnasher729
gnasher729

Reputation: 52622

I don't care what the behaviour of this code is. I care about coding standards and what they are good for. If your code depends on things that are so obscure that you have to ask questions here, then you are doing it wrong.

You should never, ever have an instance variable that doesn't start with an underscore character. Make it Node* _node instead. Now you don't have to worry about this anymore. The whole problem is gone.

Also, turn compiler warnings on so that the compiler can tell you when you are doing dangerous things.

Upvotes: 1

Related Questions