I need to know if the retaincount
of objects should always be 0
if i want to have a good memory management in my code. I got the following code from a book. and there's a statement NSLog
called after release = 2
, So should i have to release it 2 more times so that the retaincount
will be 0 ?
#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSValue.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSNumber *myInt = [NSNumber numberWithInteger: 100];
NSNumber *myInt2;
NSMutableArray *myArr = [NSMutableArray array];
NSLog (@”myInt retain count = %lx”,
(unsigned long) [myInt retainCount]);
[myArr addObject: myInt];
NSLog (@”after adding to array = %lx”,
(unsigned long) [myInt retainCount]);
myInt2 = myInt;
NSLog (@”after asssignment to myInt2 = %lx”,
(unsigned long) [myInt retainCount]);
[myInt retain];
NSLog (@”myInt after retain = %lx”,
(unsigned long) [myInt retainCount]);
NSLog (@”myInt2 after retain = %lx”,
(unsigned long) [myInt2 retainCount]);
[myInt release];
NSLog (@”after release = %lx”,
(unsigned long) [myInt retainCount]);
[myArr removeObjectAtIndex: 0];
NSLog (@”after removal from array = %lx”,
(unsigned long) [myInt retainCount]);
[pool drain];
return 0;
}
Program Output
myInt retain count = 1
after adding to array = 2
after asssignment to myInt2 = 2
myInt after retain = 3
myInt2 after retain = 3
after release = 2
after removal from array = 1
UPDATE
The following code was taken from the Apples memory management document. They have retained a NSNumber object and its never been released, is this OK ?
- (void)setCount:(NSNumber *)newCount {
[newCount retain];
[_count release];
// Make the new assignment.
_count = newCount;
}