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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With