NSNumber 的副本没有分配新内存
我正在为自定义 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 遵守但在复制时不返回新的内存地址?
谢谢利奥
I am implementing a copyWithZone method for a custom A class, in which a NSNumber pointer was declared as (retain) property
@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;
}
When I debug, I always find new.num is the same address as the self.num.
Even if I use
new.num = [NSNumber numberWithFloat: [num floatValue]];
I still get the same address. In the end, I have to use
new.num = [[[NSNumber alloc] initWithFloat:[num floatValue]] autorelease]
to achieve the result I want. I am just wondering why NSNumber complies to but does not return a new memory address when copied?
Thanks
Leo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NSNumber 是不可变的。制作副本是没有意义的,因此,当调用复制时,框架只会返回 self 。
如果一个类实现了 NSCopying,您应该将该属性标记为
copy
(而不是retain
)。不可变类 (NSString
) 上的-copy
只会返回对对象的引用(带有增加的保留计数)。如果传递一个可变实例,它将被复制到一个不可变实例。这可以防止外部人员背后更改对象的状态。NSNumber is immutable. Making a copy is pointless and, thus, the frameworks just return self when copy is invoked.
If a class implements NSCopying, you should mark the property as
copy
(notretain
).-copy
on immutable classes (NSString
) will simply return a reference to the object (w/a bumped retain count). If passed a mutable instance, it'll be copied to an immutable instance. This prevents an external party from changing the state behind your object's back.NSNumber 不仅是不可变的 - 对于低值,它也是 Flyweight。
Not only is NSNumber immutable - for low values it as also a Flyweight.
NSNumber
不可变,因此无需强制进行物理复制。NSNumber
isn't mutable, so there is no need to force physical copying.在实现 NSCopying 协议时,您应该使用 [[A alloc] initWithZone:zone] 。
正如其他人所说, NSNumber 是不可变的,因此返回相同的对象。
You should be using [[A alloc] initWithZone:zone] when implementing the NSCopying protocol.
As others have stated though, NSNumber is immutable and so returns the same object.