Question

Could someone help me please understand how allocation and memory management is done and handled in following scenario. i am giving a Psuedo code example and question thats troubling me is inline below:

interface first  
{ NSDecimalNumber *number1;  
}

implementation  
.....

-(void) dealloc {  
 [number1 release];  
 [super dealloc];  
}


=================================  
interface second  
{ NSDecimalNumber *number2;  
}  

implementation second  
.....  
- (First*) check  
{  
    First *firstObject = [[[First alloc] init] autorelease];  
    firstObject.number1 = [[NSDecimalNumber alloc] initWithInteger:0];   
                    **// do i need to autorelease number1 as well?**  
    return firstObject;  
}  
Was it helpful?

Solution

Your code is correct as is. If you autoreleased the object, its reference count would reach zero and it would be dealloced, and then if you later tried to use the value stored in number1 your app would crash.

The only enhancement I'd add is releasing any existing value. i.e.

[number1 release];
number1 = [[NSDecimalNumber alloc] initWithInteger:0];   

If you don't do this, the previous object assigned to number1 will leak each time check is called.

OTHER TIPS

As you're allocing the NSDecimalNumber, you need to release it. (As you're doing so in the dealloc.)

Whilst it's hard to provide a meaningful example based on your sample code (as "number1" isn't actually used), the general rule is that you're responsible for any object you alloc, copy or new. If the object was only required in the scope of a function, you could of course autorelease it.

There's a good blog article over at http://interfacelab.com/objective-c-memory-management-for-lazy-people/ that I'd recommend reading as it provides good examples (including some edge cases) and is easy to follow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top