Declaring Variables in @implementation

混江龙づ霸主 提交于 2019-12-22 04:49:09

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/7946998/declaring-variables-in-implementation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!