简体   繁体   中英

Objective-C equivalent of C# readonly variables

In C#, we can declare an instance variable as readonly to specify that it may only be the subject of an assignment during declaration or in the constructor of the class to which it belongs:

private readonly int _myInt;

In Objective-C, I understand that a property can be declared as readonly thus:

@property (readonly) int myInt;

However, this is equivalent to a C# property with a private set accessor and does not protect the corresponding instance variable from being reassigned "privately" after initialization.

Is there a way to mimic the behaviour of C#'s readonly modifier in Objective-C, such that an instance variable can only be assigned to in the initializer of its containing class (note that - because I would like to be able to assign to the variable during the class initializer, the const modifier does not suit my needs)?

If this is not possible, is there a conceptual reason why this behaviour would not be appropriate in Objective-C?

Objective-C is, ultimately, a C based, pointer rich, language. Thus, once you have the pointer to an instance of any given object, you can reach in and muck around with the object state quite directly and at whim. Without a VM or some other mechanism that securely enforces readonly memory within the process, any such mechanisms can be defeated.

Thus, Objective-C long ago chose simplicity over a false sense of security.

You can't reset the value of a readonly @property 's backing store from outside the class without doing something quite skanky; calling a method that isn't declared in the class's public @interface , messing about with the runtime APIs, or something worse.

So, ultimately, such features haven't been pursued exactly because doing so would consume a bunch of engineering manpower, wouldn't really add to the security of the language, and would make the language, itself, more complex (with the additional keywords and rules to remember).

Related, see this question/answer: Why doesn't Objective-C support private methods?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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