Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Pt314

macrumors newbie
Original poster
Oct 12, 2009
1
0
I understand that the retain and release methods are supposed to be for memory management. This is straight forward when I am doing things like this.

Code:
Thing* thing = [[Thing alloc] init];

//Sometime later
[thing release]

However there are a few things that still confuse me.

If I initialize a member variable which is a pointer to an external object to nil, and I expect to set it to something later, Do I release it in the dealloc?

Secondly, if I send a pointer as an argument to a method, do I retain it in the method? What if what is being passed is a @property(retain) pointer?

Here is some of the code I have been writing. I have been trying to write a class that behaves like a stack of pointers to other classes, but I think I have gotten paranoid about the memory management.

Code:
#import "Spell.h"

@interface SpellStack : NSObject 
{
	Spell* m_pSpell;
	SpellStack* m_pNext;
	
	int m_iDC, m_iPC;
}

@property(retain) Spell* m_pSpell;
@property(retain) SpellStack* m_pNext;

- (id)init : (Spell*)pIn;

- (void)push : (Spell*)pIn;
- (void)pop;

- (void)dealloc;

@end

Code:
#import "SpellStack.h"


@implementation SpellStack

@synthesize m_pSpell;
@synthesize m_pNext;

- (id)init : (Spell*)pIn
{
	m_pSpell = [pIn retain];
	m_pNext = nil;
	
	m_iDC, m_iPC = 0;
	
	return self;
}

- (void)push : (Spell*)pIn
{
	SpellStack* pOldSelf = [self copy];
	
	m_pSpell = [pIn retain];
	m_pNext = pOldSelf;
}

- (void)pop
{	
	[m_pSpell release];
	m_pSpell = [m_pNext.m_pSpell retain];
	
	SpellStack* pOldNext = m_pNext;
	m_pNext = [m_pNext.m_pNext retain];
	[pOldNext release];
}

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

@end
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.