Objective-c – Readonly Properties in Objective-C

objective cpropertiesreadonly

I have declared a readonly property in my interface as such:

 @property (readonly, nonatomic, copy) NSString* eventDomain;

Maybe I'm misunderstanding properties, but I thought that when you declare it as readonly, you can use the generated setter inside of the implementation (.m) file, but external entities cannot change the value. This SO question says that's what should happen. That is the behavior I'm after. However, when attempting to use the standard setter or dot syntax to set eventDomain inside of my init method, it gives me an unrecognized selector sent to instance. error. Of course I'm @synthesizeing the property. Trying to use it like this:

 // inside one of my init methods
 [self setEventDomain:@"someString"]; // unrecognized selector sent to instance error

So am I misunderstanding the readonly declaration on a property? Or is something else going on?

Best Answer

You need to tell the compiler that you also want a setter. A common way is to put it in a class extension in the .m file:

@interface YourClass ()

@property (nonatomic, copy) NSString* eventDomain;

@end