What's the best practice for implementing NSCopying across a two class inheritance hierarchy? I would like to have a deep copy of both Square and Shape's properties on a copy.
The 3 questions I have:
- Do both the parent and child class need to declare that they're implementing
NSCopying
or it adequate to only declare it on the base class? - I've seen some people use
[instance copy]
instead of[instance copyWithZone:]
Is this just a preference or is it more correct to use:copyWithZone
? - When copying arrays, is it correct to do:
newObj.list = [[NSArray alloc] initWithArray:self.list copyItems:YES];
Here's what I have:
@interface Shape : NSObject <NSCopying>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *sides;
@property (nonatomic, strong) NSArray *list;
@end
@implementation Shape
- (id)copyWithZone:(NSZone *)zone {
Shape *shape = [[[self class] allocWithZone:zone] init];
// Is it correct to use copyWithZone: instead of copy? eg: [self.name copy]
shape->_name = [self.name copyWithZone:zone];
shape->_sides = [self.sides copyWithZone:zone];
shape->_list = [[NSArray alloc] initWithArray:self.list copyItems:YES];
return shape;
}
@end
// Does this class also need to declare <NSCopying>?
@interface Square : Shape
@property (nonatomic, strong) NSString *color;
@property (nonatomic, strong) NSArray *corners;
@end
@implementation Square
- (id)copyWithZone:(NSZone *)zone {
// Will this ensure a deep copy of the inherited properties?
Square *square = [[[self class] allocWithZone:zone] init];
square->_color = [self.color copyWithZone:zone];
square->_corners = [[NSArray alloc] initWithArray:self.corners copyItems:YES];
return square;
}
@end