tags:

views:

948

answers:

2

Is the copyWithZone (See Below) correct, particularly the bit where I use the setters to populate the instance variables of the new object?

@interface Planet : NSObject <NSCopying>
{
    NSString *name;
    NSString *type;
    NSNumber *mass;
    int index;
}
@property(copy) NSString *name;
@property(copy) NSString *type;
@property(retain) NSNumber *mass;
@property(assign) int index;
-(void)display;
@end

-(id) copyWithZone: (NSZone *) zone {
    Planet *newPlanet = [[Planet allocWithZone:zone] init];
    NSLog(@"_copy: %@", [newPlanet self]);
    [newPlanet setName:name];
    [newPlanet setType:type];
    [newPlanet setMass:mass];
    [newPlanet setIndex:index];
    return(newPlanet);
}

EDIT_001:

Is this a better way?

-(id) copyWithZone: (NSZone *) zone {
    Planet *newPlanet = [[[self class] allocWithZone:zone] init];
    [newPlanet setName:[self name]];
    [newPlanet setType:[self type]];
    [newPlanet setMass:[self mass]];
    [newPlanet setIndex:[self index]];
    return(newPlanet);
}

many thanks

gary

+1  A: 

Whether it's an unwanted copy or not is for you to decide. The reason to synthesize accessors with the copy qualifier is to be sure of the ownership of those objects.

Keep in mind though, that immutable objects like an NSNumber or an NSString won't actually duplicate their storage when they're sent a -copy message, they'll just increase their retain counts.

NSResponder
Thats true, is this method the correct way to set the instance variables then or am I missing a better way?
fuzzygoat
+1  A: 

Have you read this guide ? If so, you have to choose whether you want a shallow or a deep copy. For shallow copies, you can share values: this is a typical approach when implementing a NSCell sublcass that share an NSImage instance.

As I don't know the context, I will say that your implementation seems correct.

Laurent Etiemble
So in the example above would this be a deepCopy as the setter creates a copy, although I do appreciate that copying an NSString on incs its retain count?
fuzzygoat