0
votes

what is convenience constructor.

if I use init method like this

 NSNumber *zero = [[NSNumber alloc] initWithInteger:0];
 [self setCount:zero];
 [zero release];

it is me to retain or release zero object. but if I do like this

NSNumber *zero = [NSNumber numberWithInteger:0];
    [self setCount:zero];

the apple documents says no need to retain or release zero.

what is the detail memory state of when using numberWithInteger:? the object returned by Class method numberWithInteger: doesn't have the retain count 1 or the zero object retain count 1? It seems the count of the object pointed by pointer zero is already 1 when returned by numberWithInteger:. If I invoke setCount:, the count plus 1 to 2. there seems a potential memory leak.

2
You get confused because of the new thing that plays an important role here: the autorelease pool.krafter

2 Answers

1
votes

It's convenience of convenience constructor, that object already moved in autorelease pool and you don't need release it.

[NSNumber numberWithInteger:0];

implemented as:

+ (NSNumber) numberWithInteger:(NSInteger) value
{
    return [[[NSNumber alloc] initWithInteger: values] autorelease];
}

You should use same patter for implementing yours own convenience constructors.

0
votes

Memory state:

1) NSNumber *zero = [[NSNumber alloc] initWithInteger:0];

During do this, it will alloc NSNumber with retain count 1. But you're responsible for to release this memory.

2) NSNumber *zero = [NSNumber numberWithInteger:0];

During do this, it will also alloc NSNumber and do assign operation. It also have retain count 1. But you don't worry about release this memory. Because this method numberWithInteger: return autorelease object. So if you will retain this object, you've to release that retain count.

Note: When the retain count of memory going to zero, it'll automatically dealloc from memory. Idea behind this memory management is retain count of allocated memory, if the allocated memory have retain count 1 or more for along time but didn't use in any run loop, it'll consider as leak.

REF: To know more about memory management , read this apple's doc.