Does @property copy in combination with readonly make sense?

前端 未结 4 2201
野的像风
野的像风 2020-12-15 17:05

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, the

相关标签:
4条回答
  • 2020-12-15 17:15

    According to Apple's documentation (which I've linked here for you):

    copy
    Specifies that a copy of the object should be used for assignment.

    The previous value is sent a release message.

    The copy is made by invoking the copy method. This attribute is valid only for object types, which must implement the NSCopying protocol.

    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.

    0 讨论(0)
  • 2020-12-15 17:24

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-15 17:36

    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:

    @interface MyClass ()
    @property (nonatomic, copy, readwrite) NSData *data;
    @end
    

    Note that the copy, readonly declaration in the public header is required in this case!

    0 讨论(0)
  • 2020-12-15 17:36

    You are correct, it does not make sense to have both.

    0 讨论(0)
提交回复
热议问题