[英]The difference between the ways of declaring a variable
I'm new to Objective-C, and I can not understand what is the difference between the declaration of variables (firstString, secondString and thirdString) in MyClass.h: 我是Objective-C的新手,我无法理解MyClass.h中的变量声明(firstString,secondString和thirdString)之间的区别是什么:
@interface MyClass {
NSString *firstString;
}
@end
in MyClass.m: 在MyClass.m中:
@interface MyClass() {
NSString *secondString;
}
@end
@implementation MyClass
NSString *thirdString;
@end
I guess that the first and the second case is the same thing, but in what case it is better to use? 我猜第一种情况和第二种情况是相同的,但是在哪种情况下最好使用?
Thanks a lot! 非常感谢!
firstString
is declared in the header, the file which is #import
ed by other classes. firstString
在标头中声明,标头由其他类#import
firstString
。 It is exposed to other classes and can therefore be accessed by subclasses and, since the symbol is available in the header file, it will be simpler for external objects to alter through key-value coding . 它公开给其他类,因此可以由子类访问,并且由于该符号在头文件中可用,因此外部对象通过键值编码进行更改将更加容易。
secondString
is declared in your implementation file. secondString
在实现文件中声明。 The ()
in @interface MyClass ()
signifies that this is a class extension . 在()
中@interface MyClass ()
表示这是一个类扩展 。 secondString
will not be exposed to external classes (though, as with everything in Objective-C, you cannot consider it to be truly private). secondString
不会公开给外部类(尽管,与Objective-C中的所有内容一样,您不能认为它是真正的私有)。
The first and second variables will be instance variables, whereas the third one will be a file-scope global variable. 第一个和第二个变量将是实例变量,而第三个将是文件范围的全局变量。 Typically you should use instance variables and avoid using global variables. 通常,您应该使用实例变量,而避免使用全局变量。
There is no functional difference between the three, it's mainly visibility control. 两者之间没有功能上的区别,主要是可见性控制。
The first one is declared in a public header of you class, that means that you want the programmers the know about the variable. 第一个在类的公共标头中声明,这意味着您希望程序员了解变量。 If the access to this property is restricted (eg @private
), it should not appear in public header anymore and you should use the second or forth option. 如果对此属性的访问受到限制(例如@private
),则该属性不应再出现在公共标头中,而应使用第二个或第四个选项。
The second is declared in the class continuation, meaning that it is needed only by the implementation. 第二个在类继承中声明,这意味着仅实现需要它。
The third one is a global variable, something you should use only in exceptional cases. 第三个是全局变量,仅在特殊情况下才应使用。
Missing another option 缺少其他选择
@implementation MyClass {
NSString *thirdString;
}
@end
(allowed by the latest Apple compilers) is the same as 2, without the need to create the class continuation. (最新的Apple编译器允许)与2相同,而无需创建类继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.