Objective-C中const实例变量的替代方案?

时间:2022-09-07 20:09:13

Since Objective-C doesn't support const instance variables in classes what are some alternatives to ensure the value of the variable doesn't get changed? I do not want to resort to preprocessor #defines because I would prefer class variables. Also, is there a reason const instance variables aren't supported?

既然Objective-C不支持类中的const实例变量,那么有什么替代方法可以确保变量的值不被改变呢?我不想使用预处理器#define,因为我更喜欢类变量。此外,是否有不支持const实例变量的原因?

1 个解决方案

#1


5  

Objects in Objective-C are constructed differently than those in C++ or Java. All instance variables are initialized to zero by the alloc method, before the init method is called, so it would be too late by the time init is called to change a const instance variable. Obviously the compiler writers could modify the compiler to support changing a const instance variable in an init method, but they haven't done so.

Objective-C中的对象构造与c++或Java中的对象不同。在调用init方法之前,alloc方法将所有实例变量初始化为0,因此在调用init来更改const实例变量时,已经太晚了。显然,编译器编写者可以修改编译器以支持在init方法中更改const实例变量,但他们还没有这样做。

Typically you just make your instance variables @private and expose them using accessor methods. If you don't want an instance variable's value to change, don't expose a setter method and don't modify the variable in your class implementation.

通常,您只需将实例变量@private并使用访问器方法公开它们。如果您不希望实例变量的值发生变化,那么不要公开setter方法,也不要在类实现中修改该变量。

If you drop support for 32-bit Mac OS X, you can put your instance variables in your @implementation instead of your @interface, which completely protects them from meddling by other classes.

如果您放弃对32位Mac OS X的支持,您可以将实例变量放在@implementation而不是@interface中,这将完全保护它们不受其他类的干扰。

#1


5  

Objects in Objective-C are constructed differently than those in C++ or Java. All instance variables are initialized to zero by the alloc method, before the init method is called, so it would be too late by the time init is called to change a const instance variable. Obviously the compiler writers could modify the compiler to support changing a const instance variable in an init method, but they haven't done so.

Objective-C中的对象构造与c++或Java中的对象不同。在调用init方法之前,alloc方法将所有实例变量初始化为0,因此在调用init来更改const实例变量时,已经太晚了。显然,编译器编写者可以修改编译器以支持在init方法中更改const实例变量,但他们还没有这样做。

Typically you just make your instance variables @private and expose them using accessor methods. If you don't want an instance variable's value to change, don't expose a setter method and don't modify the variable in your class implementation.

通常,您只需将实例变量@private并使用访问器方法公开它们。如果您不希望实例变量的值发生变化,那么不要公开setter方法,也不要在类实现中修改该变量。

If you drop support for 32-bit Mac OS X, you can put your instance variables in your @implementation instead of your @interface, which completely protects them from meddling by other classes.

如果您放弃对32位Mac OS X的支持,您可以将实例变量放在@implementation而不是@interface中,这将完全保护它们不受其他类的干扰。