[swift-users] @NSCopying semantic does not appear to copy in Swift initializer

Quinn "The Eskimo!" eskimo1 at apple.com
Mon Jan 30 04:21:12 CST 2017


On 30 Jan 2017, at 10:12, Torin Kwok <torin at kwok.im> wrote:

> In Obj-C, if a property has promised that it conforms to <NSCopying>
> porotocl and that it would respect copying semantic by being qualified
> with `@property (copy)`, then we assign a value to `ivar` through the
> setter by writting down `self.ivar = whatever` in `-init` …

You can do that if you choose to, but the Objective-C convention is to use direct ivar access in `-init` and `-dealloc`.  This is explicitly called out in the “Access Instance Variables Directly from Initializer Methods” section of “Programming with Objective-C”, which says:

> You should always access the instance variables directly from within an initialization method …

<https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW11>

For an object with a copyable property `name`, the `-init` method would look like this:

- (instancetype)initWithName:(NSString *)name {
    self = [super init];
    if (self != nil) {
        self->_name = [name copy];
    }
    return self;
}

Share and Enjoy
--
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware




More information about the swift-users mailing list