简体   繁体   English

在Objective-C中声明

[英]Declaring in Objective-C

I am very new to Objective-C programming, and I have a question that has always puzzled me: why do you have to declare your variables in the header file, like this? 我对Objective-C编程非常陌生,我有一个始终困扰着我的问题:为什么要像这样在头文件中声明变量?

@interface MyViewController : UIViewController
{
    NSString *myString;
}

Why not just declare them here (in the .m file): 为什么不在这里(在.m文件中)声明它们:

@implementation MyViewController

- (void)viewDidLoad
{
    NSString *myString;
}

The first declaration is a instance variable available to all instance methods. 第一个声明是一个实例变量,可用于所有实例方法。 The second is local to the one method. 第二种是一种方法的本地方法。

However it is possible to declare instance variables in the .m file: 但是,可以在.m文件中声明实例变量:

@implementation MyViewController {
    NSString *myString;
}

In fact this is the preferred way to declare instance variables that do not need to be exposed. 实际上,这是声明不需要公开的实例变量的首选方法。 Only declare things in the .h file that need to be available to other classes. 只在.h文件中声明需要其他类可用的内容。

There are two different questions going on here. 这里有两个不同的问题。

To put it simply, the header file (.h) is a public gateway for everything else to see what your class is about without having to know anything about your implementation. 简而言之,头文件(.h)是其他所有内容的公共网关,您无需了解任何实现即可查看类的内容。 Your header file should contain everything that you would want other classes to know about (ie public methods, properties). 您的头文件应该包含您希望其他类知道的所有内容(即公共方法,属性)。

You could easily declare things in the implementation file but then other classes would not know about them. 您可以轻松地在实现文件中声明内容,但是其他类将不知道这些内容。

Secondly, in the example you provided you have put NSString *myString; 其次,在您提供的示例中,您已放置NSString *myString; in the viewDidLoad method. 在viewDidLoad方法中。 This means that such a variable would be only available in the scope of that method. 这意味着此类变量仅在该方法的范围内可用。 Nothing else would be able to access it. 其他都无法访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM