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 ?
Either assign to the instance variable directly (don’t forget to add a
retainorcopyif you need it) or redeclare the property in a private class extension. Like this:In your .h file:
In your .m file:
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.