Readonly Properties in Objective-C?

Objective CPropertiesReadonly

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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

Solution 2 - Objective C

Eiko and others gave correct answers.

Here's a simpler way: Directly access the private member variable.

Example

In the header .h file:

@property (strong, nonatomic, readonly) NSString* foo;

In the implementation .m file:

// inside one of my init methods
self->_foo = @"someString"; // Notice the underscore prefix of var name.

That’s it, that’s all you need. No muss, no fuss.

Details

As of Xcode 4.4 and LLVM Compiler 4.0 (New Features in Xcode 4.4), you need not mess with the chores discussed in the other answers:

  • The synthesize keyword
  • Declaring a variable
  • Re-declaring the property in the implementation .m file.

After declaring a property foo, you can assume Xcode has added a private member variable named with a prefix of underscore: _foo.

If the property was declared readwrite, Xcode generates a getter method named foo and a setter named setFoo. These methods are implicitly called when you use the dot notation (my Object.myMethod). If the property was declared readonly, no setter is generated. That means the backing variable, named with the underscore, is not itself readonly. The readonly means simply that no setter method was synthesized, and therefore using the dot notation to set a value fails with a compiler error. The dot notation fails because the compiler stops you from calling a method (the setter) that does not exist.

The simplest way around this is to directly access the member variable, named with the underscore. You can do so even without declaring that underscore-named variable! Xcode is inserting that declaration as part of the build/compile process, so your compiled code will indeed have the variable declaration. But you never see that declaration in your original source code file. Not magic, just syntactic sugar.

Using self-> is a way to access a member variable of the object/instance. You may be able to omit that, and just use the var name. But I prefer using the self+arrow because it makes my code self-documenting. When you see the self->_foo you know without ambiguity that _foo is a member variable on this instance.


By the way, discussion of pros and cons of property accessors versus direct ivar access is exactly the kind of thoughtful treatment you'll read in Dr. Matt Neuberg's Programming iOS book. I found it very helpful to read and re-read.

Solution 3 - Objective C

Another way I've found to work with readonly properties is to use @synthesize to specify the backing store. For example

@interface MyClass

@property (readonly) int whatever;

@end

Then in the implementation

@implementation MyClass

@synthesize whatever = m_whatever;

@end

Your methods can then set m_whatever, since it is a member variable.


Another interesting thing I have realized in the past few days is you can make readonly properties that are writable by subclasses like such:

(in the header file)

@interface MyClass
{
    @protected
    int m_propertyBackingStore;
}

@property (readonly) int myProperty;

@end

Then, in the implementation

@synthesize myProperty = m_propertyBackingStore;

It will use the declaration in the header file, so subclasses can update the value of the property, while retaining its readonlyness.

Slightly regrettably in terms of data hiding and encapsulation though.

Solution 4 - Objective C

See Customizing Existing Classes in the iOS Docs.

> readonly Indicates that the property is read-only. If you specify readonly, only a getter method is required in the @implementation. If you use @synthesize in the implementation block, only the getter method is synthesized. Moreover, if you attempt to assign a value using the dot syntax, you get a compiler error.

Readonly properties only have a getter method. You can still set the backing ivar directly within the property's class or using key value coding.

Solution 5 - Objective C

You are misunderstanding the other question. In that question there is a class extension, declared thus:

@interface MYShapeEditorDocument ()
@property (readwrite, copy) NSArray *shapesInOrderBackToFront;
@end

That is what generates the setter only visible within the class's implementation. So as Eiko says, you need to declare a class extension and override the property declaration to tell the compiler to generate a setter only within the class.

Solution 6 - Objective C

The shortest solution is:

MyClass.h

@interface MyClass {

  int myProperty;

}

@property (readonly) int myProperty;

@end

MyClass.h

@implementation MyClass

@synthesize myProperty;

@end

Solution 7 - Objective C

If a property is defined as readonly, that means that there effectively wont be a setter that can be used either internally to the class or externally from other classes. (i.e.: You'll only have a "getter" if that makes sense.)

From the sounds of it, you want a normal read/write property that's marked as private, which you can achieve by setting the class variable as private in your interface file as such:

@private
    NSString* eventDomain;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - Objective CEikoView Answer on Stackoverflow
Solution 2 - Objective CBasil BourqueView Answer on Stackoverflow
Solution 3 - Objective CyanoView Answer on Stackoverflow
Solution 4 - Objective CJonahView Answer on Stackoverflow
Solution 5 - Objective CBoltClockView Answer on Stackoverflow
Solution 6 - Objective Cuser2159978View Answer on Stackoverflow
Solution 7 - Objective CJohn ParkerView Answer on Stackoverflow