Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c ARC readonly properties and private setter implementation

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;
   }
}
like image 373
Jonas Gardner Avatar asked Dec 19 '11 19:12

Jonas Gardner


2 Answers

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.

like image 98
Joshua Weinberg Avatar answered Nov 12 '22 03:11

Joshua Weinberg


You can redeclare your property as readwrite in interface extension:

@interface SomeClass()
@property (nonatomic, strong, readwrite) NSString *myProperty;
@end
like image 24
iHunter Avatar answered Nov 12 '22 04:11

iHunter