Cocoa Memory Management
by Jose R.C. Cruz

Listing One

theObj = [theClass new]; \\ reference count is 1

[theObj retain];         \\ reference count is 1+1 = 2
[theObj retain];         \\ reference count is 2+1 = 3
[theObj release];        \\ reference count is 3-1 = 2
[theObj release];        \\ reference count is 2-1 = 1
[theObj release];        \\ reference count is 1-1 = 0
\\ theObj then self-destructs


Listing Two

int   theCount;

theObj = [theClass new];       \\ reference count is 1
[theObj retain];               \\ reference count is 1+1 = 2
theNum = [theObj retainCount]; \\ returns the current count of 2
[theObj release];              \\ reference count is 2-1 = 1
theNum = [theObj retainCount]; \\ returns the current count of 1
[theObj release];              \\ reference count is 1-1 = 0

Listing Three

@interface anObj:NSObject
{
  NSObject    *theProp
}
-(NSObject  *) getObject;
-(void) setObject:(NSObject *)newObj;
@end


Listing Four

-(void) setObject:(NSObject *)newObj
{
[newObj retain];
[theObj release];
theProp = newObj;
}
-(NSObject *)getObject
{
return (theProp);
}


Listing Five 

-(NSObject *) getObject
{
return ([[theProp retain] autorelease]);
}


Listing Six

-(void) setObject:(NSObject *)newObj
{
   if (theProp != newObj)
   {
         [newObj retain];
         [theProp release];
         theProp = newObj;
   }
}

Listing Seven

-(void) setObject:(NSObject *)newObj
{
   if (theProp != newObj)
   {
   [theProp autorelease];
   theProp = [newObj retain];
   }
}

Listing Eight

NSObject *theObj;

theObj = [anObj getObject];
[anObj setObject:[NSObject new]];

if (theObj == [anObj getObject)
   NSLog(@"Both objects are the same");
else
   NSLog(@"Both objects are different");


Listing Nine

-(void) setObject:(NSObject *)newObj
{
   [theProp autorelease];
   theProp = [newObj retain];
}


Listing Ten 

NSAutoreleasePool       *aPool;
// instantiate the pool
aPool = [[NSAutoreleasePool alloc] init];

/* Create and autorelease a lot of objects here */
// dispose the pool
[aPool release];


Listing Eleven

NSZone            *theZone = NSCreateZone(8192, 1024, FALSE);
NSString          *theStr, *theCopy;
NSMutableString   *theMutableCopy;

// allocating an NSString from the custom zone
theStr = [NSString allocWithZone:theZone];
[theStr init];

// copying NSString using the custom zone
theCopy = [theStr copyWithZone:theZone];

// copying a mutable NSString using the custom zone
theMutableCopy = [theStr mutableCopyWithZone:theZone];


Listing Twelve

NSZone            *theZone = NSCreateZone(8192, 1024, FALSE);
 ... 
// allocate and dispose Cocoa objects
 ... 
// free all memory used by the zone
NSRecycleZone(theZone);
 ... 
// destroy the zone completely
malloc_destroy_zone(theZone);




3


