views:

64

answers:

2

I'm having trouble figuring out how to manage memory for an instance variable that needs to maintain it's current state for a period of time, then be reassigned to newly allocated memory.

Take the following example for the instance variable "importantData".:

-(void)Update
{
   importantData = [[self getObject] retain];
}


- (SomeObject *)getObject 
{
   SomeObject *objInstance = [[SomeObject alloc] init];
   [objInstance autorelease];  
   return objInstance;
}       

In my actual project, the getObject procedure is in a different class but I've simplified it just to get my point across. importantData must stay around be valid in between calls to Update.

Every time getObject is called, I'm allocating new memory and assigning it to importantData, correct? I figure I have to release the memory that importantData was pointing to before, right? I'm not sure how to do this properly without leaking memory or trying to reference deallocated memory. Thanks!

+1  A: 

You could use a static variable.

static SomeObject *importantObject = nil;

@implementation SomeObject

+ (SomeObject*)getObject {
  if (!importantObject) {
    importantObject = [[SomeObject alloc] init];
  }
  return importantObject;
}

@end

This will keep it around until the app exists. But if you want to invalidate or recreate it you could add a method like:

+ (void)expireObject {
  [importantObject release];
  importantObject = nil;
}

Or even

+ (void)setObject:(SomeObject*)newObject {
  [importantObject release];
  importantObject = [newObject retain];
}

And you can now use importantObject in SomeObject's class and instance methods, or fetch it from other classes via SomeObject's class method getter.

Squeegy
+1  A: 

You just need update to look like this:

-(void)Update
{
   [importantData release];
   importantData = [[self getObject] retain];
}

Basically, just remember to release before you assign a new value.

Kendall Helmstetter Gelner