Arildo Junior
Arildo Junior

Reputation: 786

Declaring Variables in @implementation

I saw an example in a book showing this code:

@implementation ViewController
{
    NSString *name;
}

Why not declare this in @interface? What's the difference in declaring variables in @implementation instead of @interface? Why declare this NSString in a scope?

Upvotes: 7

Views: 1946

Answers (1)

Ole Begemann
Ole Begemann

Reputation: 135548

The advantage of declaring ivars in the @implementation section is better encapsulation. That way, ivars don't have to appear in the .h file and are therefore not visible to external users of your class who only get to see the header file. This better hides the internal implementation of the class.

Generally speaking, now that properties can have auto-synthesized ivars and other ivars can be declared directly in the @implementation block, I see no reason why you should declare an ivars at all in your @interface (apart from backwards compatibility).

Why declare this NSString in a scope?

Because that's the only way to declare an instance variable. Otherwise you would declare a variable that could be accessed from anywhere in the same file (see the question BoltClock linked to in his comment).

Upvotes: 8

Related Questions