简体   繁体   English

objective-c ARC只读属性和私有setter实现

[英]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: 在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

With ARC, if I wanted to override setMyProperty, you can't use retain/release keywords anymore so is this adequate and correct? 使用ARC,如果我想覆盖setMyProperty,则不能再使用retain / release关键字,这是否足够正确?

// 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. 在类扩展中,您实际上可以重新指定@property声明。

@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: 您可以在接口扩展中将您的属性重新声明为readwrite

@interface SomeClass()
@property (nonatomic, strong, readwrite) NSString *myProperty;
@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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