Objective C - 静态成员和常量
之间有什么区别
@interface SomeClass : NSObject {
NSObject *something;
}
:和
@interface SomeClass : NSObject {
}
NSObject *something;
?另外,Java的final和Objective C (C)的const有什么区别?对于以下情况,我应该在哪里声明静态类成员: 1. 当只有类需要它时 **2.**哪里是其他类可以读取的属性?我已经了解 #define,但这对对象不利,因为它每次都会创建新对象。谢谢!
Whats the difference between:
@interface SomeClass : NSObject {
NSObject *something;
}
and
@interface SomeClass : NSObject {
}
NSObject *something;
? Also, what's the difference between Java's final and Objective C (C)'s const? And where should I declare static class members for the following situations: 1. When only the class needs it **2.**Where it would be a property that other classes could read ? I already know about #define, but that isn't good for objects because it creates new ones each time. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
前者是一个实例变量,为 SomeClass 的每个实例创建一个
something
。它类似于C的后者声明了一个与SomeClass没有真正关联的全局变量。在C中,它相当于
在全局范围内定义。 Objective-C 并没有真正的类变量,因此使用全局变量(相反,有时使用;具有 编译单元范围和静态存储类是应该使用的)。
定义“类”变量的最简洁方法是在实现文件中定义静态变量。这样,只有类方法可以访问它,并且可以避免污染全局名称空间。如果您希望它公开可用,请定义访问器。
正确地销毁类变量可能很棘手。当应用程序退出时,内存将被回收,打开的文件将被自动关闭,但其他资源可能不会处理得那么好。
The former is an instance variable and creates a
something
for each instance of SomeClass. It's similar to C'sThe latter declares a global variable that has no real association with SomeClass. In C, it's equivalent to
defined in global scope. Objective-C doesn't really have class variables, so global variables are used (rather, are sometimes used; variables with compilation unit scope and static storage class are what should be used).
The cleanest way of defining a "class" variable is to define a static variable in the implementation file. That way, only the class methods can access it and you avoid polluting the global namespace. If you want it publicly available, define accessors.
Destroying class variables properly can be tricky. Memory will be reclaimed and open files will be closed automatically when the application exits, but other resources may not be handled so well.
至于“final vs const”问题,两者是相似的。他们声明该值无法更改。请注意,在 Java 中,由于所有值(除了基元)都是指针,因此它指向的对象可能会在底层发生变化,但内存位置(指针)永远不会改变。我相信您会期望 Objective C 中有类似的行为,并且不允许可变元素为“final”或“const”始终是一个好主意,因为对象内的值仍然可以修改。
As to the "final vs const" question, both are similar. They state that the value cannot change. note that in Java, as all values (except primitives) are pointers, the object it is pointing to could change underneath, but the memory location (the pointer) will never change. I believe you would expect similar behavior in Objective C, and it is always a good idea to not allow elements that are mutable be "final" or "const" as the values inside the object can still be modified then.