iphone - objective-c ARC 只读属性和私有(private) setter 实现

标签 iphone objective-c ios automatic-ref-counting

在 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/

相关文章:

ios - Branch.io 在web端生成链接,然后在app中获取

ios - 如何取消 UICollectionView 的拖动?

ios - 当之前的应用程序处于拒绝状态且上诉仍处于开放状态时,请提交新的应用程序版本

iphone - 使用 Evernote API 创建笔记

javascript - ios 的 Phonegap 插件...javascript 部分

ios - 如何修复框架错误?

ios - 什么时候应该使用 __bridge 与 CFBridgingRelease/CFBridgingRetain?

iphone - 使用 NSNumbers 优于整数或 float 的优势?

iphone - 内存管理,ARC - 什么是零?

iphone - Objective C - 将对象数组(带有日期字段)转换为数组字典(按星期几键控)