A O A O - 19 days ago 8
Objective-C Question

Is it okay to set properties on a readonly object in Objective-C

I have a

readonly
object property:

@property (readonly) MyCustomController* customController;


MyCustomerController
has a property called
myCustomProperty


Is it okay to set the property on the
readonly
object?

self.customController.myCustomProperty = [CustomProperty new];


The compiler isn't complaining, and at runtime functionality seems to be fine-- it just seems a little weird that I can set properties on a
readonly
object?

Though technically I guess I am "reading" the property, and then setting a property on it, so I'm technically not setting the actual
readonly
property pointer.

Is it bad practice to do this? Could anything go wrong?

According to Rypress:


The readonly attribute is an easy way to make a property read-only. It
omits the setter method and prevents assignment via dot-notation, but
the getter is unaffected. As an example, let’s change our Car
interface to the following. Notice how you can specify multiple
attributes by separating them with a comma.


So it seems like it isn't an issue, I just wanted to double check

CRD CRD
Answer

Though technically I guess I am "reading" the property, and then setting a property on it, so I'm technically not setting the actual readonly property pointer.

Exactly. It is not the object that is read-only, but your property which stores a reference to the object. You cannot change which object the property references, but you can call methods and properties on that object which alter its state.

What you are doing is perfectly correct and normal.