7

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?

0

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

So if I declare that NSString out of scope, would it become a global variable? I mean any external classes could access the variable?
Sort of; see the question that some thought was a dupe as it covers the difference between ivars and globals/statics. Note that ivar declarations in the @implementation is relatively new -- it wasn't possible in the 32 bit Mac OS X runtime because of the way the compiler generated classes. Once the "fragile base class" problem was solved, it became possible to do auto-synthesis and/or declare ivars outside of the primary @interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.