I was trying to create a property which is readonly. I wanted to initialize with a value from the class creating an instance of this class, e.g.
@property (retain,readonly) NSString *firstName;
And I tried to initialize it like this:
-(id)initWithName:(NSString *)n{ self.firstName = n; }
Once I did this, the compiler reported an error that the readonly property cannot be assigned. So how can i do this ?
To create a read-only field, use the readonly keyword in the definition. In the case of a field member, you get only one chance to initialize the field with a value, and that is when you call the class constructor. Beyond that, you'll would get an error for such attempt.
In c#, you can initialize the readonly fields either at the declaration or in a constructor. The readonly field values will evaluate during the run time in c#. Once values assign to the read-only fields, those values must be the same throughout the application.
The readOnly property sets or returns whether a text field is read-only, or not. A read-only field cannot be modified. However, a user can tab to it, highlight it, and copy the text from it.
Read only means that we can access the value of a property but we can't assign a value to it. When a property does not have a set accessor then it is a read only property. For example in the person class we have a Gender property that has only a get accessor and doesn't have a set accessor.
Either assign to the instance variable directly (don't forget to add a retain
or copy
if you need it) or redeclare the property in a private class extension. Like this:
In your .h file:
@property (readonly, copy) NSString *firstName;
In your .m file:
@interface MyClass () // Redeclare property as readwrite @property (readwrite, copy) NSString *firstName; @end @implementation MyClass @synthesize firstName; ...
Now you can use the synthesized setter in your implementation but the class interface still shows the property as readonly. Note that other classes that import your .h file can still call -[MyClass setFirstName:]
but they won't know that it exists and will get a compiler warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With