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 = [开发者_C百科[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
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 (not retain).  -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.
Not only is NSNumber immutable - for low values it as also a Flyweight.
NSNumber isn't mutable, so there is no need to force physical copying.
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.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论