69

I'd like to use the @property syntax to declare a synthesized property that is publicly readonly but has a setter that can be called privately from within the class.

Since it's Objective-C, this basically means that the setFoo: method would be synthesized, but calling it outside of the class itself would result in a warning (unrecognized selector). To trigger the warning I have to declare the property readonly; is there any way to force a synthesized setter that is only available within the class?

2 Answers 2

118

I think what you're looking for are called class extensions. You would declare the property read-only in the header:

@interface MyClass : NSObject {
}

@property (readonly, assign) NSInteger myInteger;

@end

Then redeclare in your class extension in the implementation file:

@interface MyClass ()

@property (readwrite, assign) NSInteger myInteger;

@end


@implementation MyClass

@end

For more check out Apple's documentation

5
  • 1
    You're correct, see also stackoverflow.com/questions/743586/…
    – Adam Ernst
    Feb 15, 2011 at 19:17
  • 3
    This is a great way to leverage the convenience of properties while maintaining necessary encapsulation. :) Love this capability.
    – CIFilter
    Feb 15, 2011 at 21:03
  • 5
    Updated documentation link: developer.apple.com/library/mac/documentation/Cocoa/Conceptual/… May 16, 2013 at 17:58
  • 1
    Did anyone actually test this? Attempting to set the property using dot notation gets a compiler error (good), but using the setMyInteger: method only gets a compiler warning, and when the app is run the "readonly" property does get changed.
    – jk7
    Jun 14, 2016 at 1:25
  • 1
    @jk7 That is correct behavior; the compiler is telling you you are doing it wrong. The runtime is "free" to violate this.
    – bbum
    Dec 5, 2019 at 20:52
1

I might be late, but without extension i did using the following technique

@interface MyClass : NSObject {
 NSString * name;
}

@property (readonly, strong) NSString * name;

@end

on the other hand in implementation file

@implementation MyClass
 @synthesize name;

 - (id)initWithItems:(NSDictionary *)items {
self = [super init];
if(self)
{ 
  name = @"abc";
}

return self;
}

@end

doing so it will set your value and will be accessible as readonly. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.