Prior to ARC, if I wanted a property to be readonly to using it but have it writeable within the class, I could do:
// Public declaration
@interface SomeClass : NSObject
@property (nonatomic, retain, readonly) NSString *myProperty;
@end
// private interface declaration
@interface SomeClass()
- (void)setMyProperty:(NSString *)newValue;
@end
@implementation SomeClass
- (void)setMyProperty:(NSString *)newValue
{
if (myProperty != newValue) {
[myProperty release];
myProperty = [newValue retain];
}
}
- (void)doSomethingPrivate
{
[self setMyProperty:@"some value that only this class can set"];
}
@end
With ARC, if I wanted to override setMyProperty, you can't use retain/release keywords anymore so is this adequate and correct?
// interface declaration:
@property (nonatomic, strong, readonly) NSString *myProperty;
// Setter override
- (void)setMyProperty:(NSString *)newValue
{
if (myProperty != newValue) {
myProperty = newValue;
}
}
Yes, that is adequate, but you don't even need that much.
You can do
- (void)setMyProperty:(NSString *)newValue
{
myProperty = newValue;
}
The compiler will do the right thing here.
The other thing though, is you don't even need THAT. In your class extension you can actually respecify @property
declarations.
@interface SomeClass : NSObject
@property (nonatomic, readonly, strong) NSString *myProperty;
@end
@interface SomeClass()
@property (nonatomic, readwrite, strong) NSString *myProperty;
@end
Doing that, you just need to synthesize and you have a private setter that is synthesized for you.
You can redeclare your property as readwrite
in interface extension:
@interface SomeClass()
@property (nonatomic, strong, readwrite) NSString *myProperty;
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With