Dear All,
I'm trying to implement NSCopying for a NSTextFieldCell based class. But I'm getting crashes all the time, because there is an array in the new class. Here is the code:
class myTextFieldCell: NSTextFieldCell { var thearray: [Int] = [] override func copy(with zone: NSZone?) -> Any { let copy = super.copy(with: zone) as! myTextFieldCell copy.thearray = [] return copy } }
It crashes all the time, no matter how the NSCopying is implemented, and I've tried all the options I can think of:
1. Copy the arrray as it is - copy.thearray = self.thearray
2. Initialize the array (as shown in the code above)
Any help on how to implement NSCopying in this situation will be highly appreciated.
I. Nikolov
Crashes how? And when?
It would be helpful if you could include a few entries from the top of the backtrace at the time of the crash.
Creating a copy by invoking super.copy is very risky, because you don't know what it does with the storage for your instance variables. This is complicated by the fact that an array property wraps an object reference, but you don't know exactly how Swift is handling this.
In particular, if the instance variable storage for you array contains trash or all zero bits after invoking super.copy, assigning to it may well crash because the old value is invalid. (The assignment would "fix" it, but you might not get that far.)
Or, more subtly, an object reference might be copied but not retained, leading to an overrelease when you make the array assignment.
If there's any way you can proceed without subclassing NSTextFieldCell at all, your code will be safer. NSCells are pretty much obsolete these days, at least for new 3rd-party development.