I have a Singleton class called Constants and I need to set some app wide constants in there. Id like these constants to be readonly. So I did the following in the Constants.h file
@interface Constants : NSObject
{
}
@property (nonatomic, readonly)double U_LAT;
@property (nonatomic, readonly)double U_LNG;
Then in my .m fileI got this method
-(id)init
{
self = [super init];
self.U_LAT = 49.2765;
self.U_LNG = -123.2177;
return self;
}
I get this error from this code:
Assignment to readonly property
Can I not initialize my readonly variable in the init method? If not how do I initialize them?
self.propertyName = val;is the same as[self setPropertyName:val];— it requires a setter method to exist. Read-only properties don’t have setter methods.You can set the ivar which backs the property directly, however:
The ivar’s name will be the property name prefixed with an underscore if you are allowing the properties to be synthesized automatically. If you have an explicit
@synthesize propName;, the ivar will have the same name. You can also create a variable with any name you like, again using a synthesize statement:@synthesize cat = dog;It’s also possible for the property to be read-only publicly, but be writeable by the class; this involves either declaring a setter method in a class extension or redeclaring the property in the extension.