Re: NSCopyObject is a disaster (was Re: Another NSOutlineView issue)
Re: NSCopyObject is a disaster (was Re: Another NSOutlineView issue)
- Subject: Re: NSCopyObject is a disaster (was Re: Another NSOutlineView issue)
- From: Quincey Morris <email@hidden>
- Date: Wed, 08 Aug 2012 16:47:15 -0700
On Aug 8, 2012, at 16:21 , Graham Cox <email@hidden> wrote:
> This opens up a whole big can of worms about implementing copy.
>
> If a superclass implements copies using NSCopyObject, then any pointer ivars we add in a subclass need to be additionally -retained. But if the superclass implements copy by alloc/initing a new object and setting properties, then this extra step would lead to an over-retain and so leak.
>
> But how can we know what approach the superclass has taken? It's not documented and we don't have the source. Aren't we supposed to be immune from implementation details like this? Or is it just a case of after a while the experienced Cocoaista "just knows" what to do in each case? This is only just rearing its head for me after almost 10 years...
It seems to me that you need to think of 'copyWithZone:' as a kind of 'init…' method, and it should therefore *not* use properties to change the instance variables that belong to the subclass, but change them directly. This is actually documented:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html
> "Your options for implementing this protocol are as follows:
> […]
> • Implement NSCopying by invoking the superclass’s copyWithZone: when NSCopying behavior is inherited. If the superclass implementation might use the NSCopyObject function, make explicit assignments to pointer instance variables for retained objects."
In other words, after calling 'super copyWithZone:', you should immediately fix (zero or overwrite) or retain your instance variables, if they're strong.
That doesn't work with ARC, of course. But this is also addressed in documentation:
http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html
> "What do I have to do when subclassing NSCell or another class that uses NSCopyObject?
>
> Nothing special. ARC takes care of cases where you had to previously add extra retains explicitly. With ARC, all copy methods should just copy over the instance variables."
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden