Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Arildo Junior Avatar asked Oct 30 '11 18:10

Arildo Junior


1 Answers

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).

like image 162
Ole Begemann Avatar answered Nov 14 '22 02:11

Ole Begemann