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

Torin Kwok torin at kwok.im
Mon Jan 30 04:43:14 CST 2017


Haha yes, you're right. I misunderstanded your idea, sorry. Indeed, in
Obj-C, we have the freedom to decide on whether or not assign a value to
a property by invoking setter or by accessing ivar directly and Apple's
official documentation apparently suggested that we should always access
the instance variables directly from within an initialization
method. That's reasonable, necessary and the best practice as well.

But I suppose what's the really tricky is not "whether we should invoke
setter in initializers" but the confusion made by the inconsistency of
`@NSCopying` attribute's behaviour in Swift.

I have reposted this issue on **swift-evolution** list, please see some
particular replies about that within this thread here:

- <https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170123/031055.html>

- <https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170123/031056.html>

Thanks!

Quinn The Eskimo! via swift-users writes:

> 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


-- 
Torin Kwok (郭桐)
OpenPGP/GnuPG: https://keybase.io/kwok


More information about the swift-users mailing list