objective-c ARC只读属性和私有setter实现 [英] objective-c ARC readonly properties and private setter implementation

查看:102
本文介绍了objective-c ARC只读属性和私有setter实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ARC之前,如果我想让一个属性只读它而在课堂上可写,我可以这样做:

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

使用ARC,如果我想覆盖setMyProperty,你不能再使用保留/释放关键词了,这是否足够正确?

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.

你可以做到

- (void)setMyProperty:(NSString *)newValue
{ 
      myProperty = newValue;
}

编译器会在这里做正确的事情。

The compiler will do the right thing here.

另一方面,你甚至不需要它。在您的类扩展中,您实际上可以重新指定 @property 声明。

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

这样做,你只需要合成,你就拥有了一个私有的setter是为你合成的。

Doing that, you just need to synthesize and you have a private setter that is synthesized for you.

这篇关于objective-c ARC只读属性和私有setter实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆