iphone - NSNumber 的副本没有分配新内存

标签 iphone objective-c ios cocoa-touch

我正在为自定义 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/

相关文章:

ios - 尝试访问另一个类型为 "Dictionary<String, Double>"的变量中的实例变量时出错

iphone - 应用程序在后台时如何处理套接字连接事件?

ios - UIButton 边框在被选中时改变粗细

ios - 什么时候在 iOS 开发中使用多线程?

ios - Storyboard 不接受 UIView 的某些尺寸

ios - 使用 UISegmentedControl 撤消选择

iphone - 核心运动(相对旋转)

ios - 在导航 Controller 中设置后退按钮

objective-c - 如何解决错误 : linker command failed with exit code 1 (use -v to see invocation) in Xcode5

ios - 在 View Controller 出现之前,Objective C 中的 IBOutlet 为零