简体   繁体   中英

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;
   }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM