[英]Does @property copy in combination with readonly make sense?
If I understand this correctly, copy
enforces the setter to create a copy of the object passed in. However, if I use it together with readonly
, there won't be a setter.如果我理解正确,
copy
会强制 setter 创建传入对象的副本。但是,如果我将它与readonly
一起使用,则不会有 setter。 So is my assumption correct, that combining @property (copy, readonly)
doesn't make any sense or am I missing something?那么我的假设是否正确,结合
@property (copy, readonly)
没有任何意义或者我错过了什么?
It does make sense.这确实有道理。 For instance, if you want to access a property's setter in your implementation only:
例如,如果您只想在实现中访问属性的设置器:
@interface MyClass : NSObject
@property (nonatomic, copy, readonly) NSData *data;
- (id)initWithData:(NSData *)data;
@end
and in the class continuation in the .m
file:并在
.m
文件中的类延续中:
@interface MyClass ()
@property (nonatomic, copy, readwrite) NSData *data;
@end
Note that the copy, readonly
declaration in the public header is required in this case!请注意,在这种情况下,需要在公共标头中
copy, readonly
声明!
According to Apple's documentation (which I've linked here for you):根据Apple的文档(我在这里为您链接):
copy
Specifies that a copy of the object should be used for assignment.指定应使用对象的副本进行分配。
The previous value is sent a
release
message.先前的值被发送一个
release
消息。The copy is made by invoking the
copy
method.复制是通过调用
copy
方法来制作的。 This attribute is valid only for object types, which must implement theNSCopying
protocol.此属性仅对必须实现
NSCopying
协议的对象类型有效。
So yes, you're correct... readonly
creates a getter method and copy
would be effectively ignored, since there's no setter method that does assignment.所以是的,你是对的......
readonly
创建了一个 getter 方法,而copy
将被有效地忽略,因为没有 setter 方法可以进行赋值。
你是对的,两者兼有是没有意义的。
I think, if I saw such a property, on read, I would expect to receive a distinct returned object to the ivar unless the returned object was advertised to be immutable.我认为,如果我在读取时看到这样的属性,我希望收到一个不同的返回对象到 ivar,除非返回的对象被宣传为不可变的。
If I have如果我有
@property (readonly, copy) NSMutableArray* foo;
and I do this:我这样做:
NSMutableArray* myFoo = [theObject foo];
[myFoo addObject: @"string"];
NSMutableArray* myOtherFoo = [theObject foo];
I would expect myOtherFoo
not to have the extra string in it that myFoo
has.我希望
myOtherFoo
中没有myFoo
具有的额外字符串。
Note: I haven't verified this yet.注意:我还没有验证这一点。
I have checked it now and my expectation is incorrect.我现在已经检查过了,我的期望是不正确的。 I think I would regard that as a bug.
我想我会认为这是一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.