fdh fdh - 11 months ago 45
Objective-C Question

Alternatives to const instance variables in Objective-C?

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?


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.

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.

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.