copyWithZone (见下文)是否正确,特别是我使用setter填充新对象的实例变量的部分?
@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:
这是一种更好的方式吗?
-(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);
}非常感谢
加里
发布于 2010-01-06 21:45:42
它是否是不想要的副本由您决定。使用copy限定符合成访问器的原因是为了确保这些对象的所有权。
但是请记住,像NSNumber或NSString这样的不可变对象在收到-copy消息时实际上不会复制它们的存储空间,它们只会增加它们的保留计数。
发布于 2012-07-11 23:04:19
(假设深度复制是您想要的)对于我们要制作的副本,使用copyWithZone:表示对象实例变量,并使用=简单地设置原始实例变量。
- (id)copyWithZone:(NSZone *)zone
{
MyClass *copy = [[MyClass alloc] init];
// deep copying object properties
copy.objectPropertyOne = [[self.objectPropertyOne copyWithZone:zone] autorelease];
copy.objectPropertyTwo = [[self.objectPropertyTwo copyWithZone:zone] autorelease];
...
copy.objectPropertyLast = [[self.objectPropertyLast copyWithZone:zone] autorelease];
// deep copying primitive properties
copy.primitivePropertyOne = self.primitivePropertyOne
copy.primitivePropertyTwo = self.primitivePropertyTwo
...
copy.primitivePropertyLast = self.primitivePropertyLast
// deep copying object properties that are of type MyClass
copy.myClassPropertyOne = self.myClassPropertyOne
copy.myClassPropertyTwo = self.myClassPropertyTwo
...
copy.myClassPropertyLast = self.myClassPropertyLast
return copy;
}但请注意,必须在不使用copyWithZone:的情况下设置与self和copy相同的类的属性。否则,这些对象将再次调用此copyWithZone,并尝试使用copyWithZone设置它们的myClassProperties。这会触发不想要的无限循环。(而且,您可以调用allocWithZone:而不是alloc:,但我非常确定alloc:无论如何都会调用allocWithZone:)
在某些情况下,使用=来深度复制同一类的对象属性可能不是您想要做的事情,但在所有情况下(据我所知),使用copyWithZone:或任何调用copyWithZone:的东西来深度复制同一类的对象属性都会导致无限循环。
发布于 2010-01-06 22:18:07
你读过this guide吗?如果是这样的话,你必须选择你想要浅的还是深的副本。对于浅层复制,您可以共享值:这是实现共享NSImage实例的NSCell子类时的典型方法。
因为我不知道上下文,所以我会说你的实现似乎是正确的。
https://stackoverflow.com/questions/2012845
复制相似问题