在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
Run Code Online (Sandbox Code Playgroud)
使用ARC,如果我想覆盖setMyProperty,则不能再使用retain/release关键字,这是否足够正确?
// interface declaration:
@property (nonatomic, strong, readonly) NSString *myProperty;
// Setter override
- (void)setMyProperty:(NSString *)newValue
{
if (myProperty != newValue) { …Run Code Online (Sandbox Code Playgroud) 在我的界面(.h)文件中,我有
@property(readonly) NSString *foo;
Run Code Online (Sandbox Code Playgroud)
在我的实现(.m)文件中,我有
@synthesize foo;
Run Code Online (Sandbox Code Playgroud)
启用ARC后,编译器会给出以下错误:自动引用计数问题:ARC禁止使用未指定的所有权或存储属性合成Objective-C对象的属性.
该错误消失,如果我加入strong,weak或copy以财产.为什么是这样?为什么在只读属性这些东西之间会有任何差异,这些差异是什么,为什么程序员必须担心它们?为什么编译器不能智能地推导出只读属性的默认设置?
我在谈论它的另一个问题:strong,weak或者copy是ARC中唯一有意义的事情,对吧?我不应该使用retain和assign了,要这样呢?
应该使用
@property (nonatomic, weak, readonly)
要么
@property (nonatomic, readonly)?
如果它被解除分配,那么弱的优点是可以将实例排除在外,但是它只是意味着弱吗?如果它想要弱行为,是否应该明确声明属性为弱?
在Objective-C中,将NSString/NSArray/NSDictionary声明为副本是常见的,是否有必要为readonly属性执行此操作,或者没有区别?如果NSString是只读的,它将永远不会被设置,因此声明强大或复制将具有相同的效果吗?
//在这里使用强而非复制,因为它永远不会被复制,所以它会起作用吗?
@property(nonatomic,readonly)NSString*string;