Search code examples
objective-cmemory-managementdeclared-property

Are declared property attributes overridden when implementing custom accessor methods?


Suppose I declare a property like so

@property (nonatomic, copy) NSObject *property;

Then I create a custom setter method

- (void) setProperty:(NSObject *)property
{
    _property = property;

    // Some more code here
}

Does the compiler interpret the copy keyword so that this setter function is equivalent to this?

_property = [property copy];

Or is it my responsibility to write it this way so that the keyword matches the behavior?


Solution

  • From "4.1.1 Property declarations" in the Clang/ARC documentation (emphasis added):

    • copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
    • ...

    A property’s specified ownership is preserved in its metadata, but otherwise the meaning is purely conventional unless the property is synthesized. If a property is synthesized, then the associated instance variable is the instance variable which is named, possibly implicitly, by the @synthesize declaration. If the associated instance variable already exists, then its ownership qualification must equal the ownership of the property; otherwise, the instance variable is created with that ownership qualification.

    So in your case, with a custom setter, declaring the property as "copy" implies that the associated instance variable _property is __strong but nothing else.

    It is your responsibility that the setter actually makes a copy, for example:

    - (void) setProperty:(NSObject *)property
    {
        _property = [property copy];
        // Some more code here
    }