[英]objective-c ARC readonly properties and private setter implementation
在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,则不能再使用retain / release关键字,这是否足够正确?
// 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.