¿Es correcto el copyWithZone (ver más abajo), particularmente el bit donde utilizo los setters para rellenar las variables de instancia del nuevo objeto?copyWithZone configurando variables de instancia?
@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:
¿Es esta una manera mejor?
-(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);
}
muchas gracias
Gary
Ambos funcionan, pero la segunda forma tiene invocaciones innecesarias de métodos. – NSResponder
@NSResponder: supongo que si escribe antes de regresar (nuevoPlanet); algo como [self setMass: a_new_number], cambiará el nuevo valor dePlanet.mass, ya que se conserva. ¿No es así? – Oliver