Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber's copy is not allocating new memory

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

like image 619
leo Avatar asked May 23 '11 15:05

leo


1 Answers

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.

like image 137
bbum Avatar answered Sep 22 '22 02:09

bbum