我正在为自定义 A 类实现一个 copyWithZone 方法,其中一个 NSNumber 指针被声明为(保留)属性
@class A <NSCopying>
{
NSNumber *num;
}
@property (nonatomic, retain) NSNumber *num; // synthesized in .m file
-(id) copyWithZone:(NSZone*) zone {
A *new = [[A alloc] init];
new.num = [num copy];
return new;
}
当我调试时,我总是发现 new.num 与 self.num 的地址相同。
即使我用
new.num = [NSNumber numberWithFloat: [num floatValue]];
我仍然得到相同的地址。最后,我不得不使用
new.num = [[[NSNumber alloc] initWithFloat:[num floatValue]] autorelease]
达到我想要的结果。我只是想知道为什么 NSNumber 遵守但在复制时不返回新的内存地址?
谢谢
狮子座
最佳答案
NSNumber 是不可变的。复制是没有意义的,因此,框架只会在调用复制时返回 self。
如果一个类实现了 NSCopying,您应该将该属性标记为 copy
(而不是 retain
)。不可变类 (NSString
) 上的 -copy
将简单地返回对对象的引用(w/a bumped retain count)。如果传递了一个可变实例,它将被复制到一个不可变实例。这可以防止外部方在您的对象背后更改状态。
关于iphone - NSNumber 的副本没有分配新内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099667/