Copy NSNumber does not allocate new memory

I am implementing the copyWithZone method for user class A in which the NSNumber pointer was declared as a property (save)

@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 - this is the same address as 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 that I want. I'm just wondering why NSNumber matches but doesn't return a new memory address when copying?

thank

Leo

+5
source share
4 answers

NSNumber is unchanged. Creating a copy is pointless and thus frameworks simply return themselves when the copy is called.

NSCopying, copy (not retain). -copy (NSString) ( ). , . .

+10

NSNumber - Flyweight.

+10

NSNumber , .

+3

NSCopying [[A alloc] initWithZone: zone].

, NSNumber .

-2

All Articles