在 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
这样做,您只需要进行综合,并且您有一个为您综合的私有(private) setter。
关于iphone - objective-c ARC 只读属性和私有(private) setter 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8566671/