Clarification: the question is not about mutable vs immutable but about a call to super creating an instance of the correct class. I hadn't thought of using [[self class] alloc]
in the base class, and this seems to solve my issues. I'll accept that anser in the next few hours if nothing better comes up :)
If a subclass inherits NSMutableCopying from its superclass and declares
additional instance variables, the subclass has to override mutableCopyWithZone:
to properly handle its own instance variables, invoking the superclass’s
implementation first.
That's very confusing. Consider
@interface Base : NSObject<NSMutableCopying>
@property (nonatomic, assign) NSInteger value ;
@end
@implementation Base
...
@end
@interface Derived : Base<NSMutableCopying>
@property (nonatomic, assign) NSInteger value2 ;
@end
@implementation Derived
- (id) mutableCopyWithZone: (NSZone *) zone {
// Huh ???
Derived * derived = [super mutableCopyWithZone: zone] ;
...
// Huh ??????
derived.value2 = self.value2 ;
return derived ;
}
...
@end
I just do not understand how this code could possibly be correct if I follow the spec.
When the call to [super mutableCopyWithZone: zone]
returns, I am expecting that the base class has only allocated enough room for its own ivars. There's no way it can tell that Derived
instances need more room for its own ivars.
What is it that the documentation means, really? How should I implement this?