在@implementation中声明变量 [英] Declaring Variables in @implementation

查看:504
本文介绍了在@implementation中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一本书中看到一个显示此代码的示例:

I saw an example in a book showing this code:

@implementation ViewController
{
    NSString *name;
}

为什么不在 @interface ?在 @implementation 中声明变量而不是 @interface 有什么区别?为什么在范围中声明这个 NSString

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?

推荐答案

ivars中的 @implementation 部分是更好的封装。这样,ivars不必出现在 .h 文件中,因此对于只看到头文件的类的外部用户是不可见的。这更好地隐藏了类的内部实现。

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.

一般来说,现在属性可以有自动合成的ivar,其他ivars可以直接在 @implementation 块,我没有理由你应该在你的 @interface 中声明一个ivars(除了向后兼容性)。 / p>

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


为什么要在范围内声明此NSString?

Why declare this NSString in a scope?

因为这是声明一个实例变量的唯一方法。否则,你将声明一个变量,可以从同一文件中的任何地方访问(参见BoltClock在他的评论中链接到的问题)。

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

这篇关于在@implementation中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆