objective-c ARC只读属性和私有setter实现
在ARC之前,如果我想让一个属性只读来使用它,但是可以在课堂上书写,我可以这样做:
// 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
用ARC,如果我想覆盖setMyProperty,你不能使用保留/释放关键字了,所以这是否足够和正确?
// interface declaration: @property (nonatomic, strong, readonly) NSString *myProperty; // Setter override - (void)setMyProperty:(NSString *)newValue { if (myProperty != newValue) { myProperty = newValue; } }
是的,这是足够的,但你甚至不需要那么多。
你可以做
- (void)setMyProperty:(NSString *)newValue { myProperty = newValue; }
编译器会在这里做正确的事情。
另一件事是,你甚至不需要这个。 在你的类扩展中,你可以重新指定@property
声明。
@interface SomeClass : NSObject @property (nonatomic, readonly, strong) NSString *myProperty; @end @interface SomeClass() @property (nonatomic, readwrite, strong) NSString *myProperty; @end
这样做,你只需要综合,你有一个专为你合成的私人二传手。
您可以在界面扩展中将您的属性重新声明为readwrite
:
@interface SomeClass() @property (nonatomic, strong, readwrite) NSString *myProperty; @end