Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 17. Memory Management > Reference Counting and Strings

Reference Counting and Strings

Program 17.2 shows how reference counting works for string objects.

Program 17.2.

90
// Reference counting with string objects

#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>

int main (int argc, char *argv[])
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSString          *myStr1 = @"Constant string";
  NSString          *myStr2 = [NSString stringWithString:
                                  @"string 2"];
  NSMutableString   *myStr3 = [NSMutableString stringWithString:
                                  @"string 3"];
  NSMutableArray  *myArr = [NSMutableArray array];

  printf ("Retain count: myStr1: %x, myStr2: %x, myStr3: %x\n",
          [myStr1 retainCount], [myStr2 retainCount],
          [myStr3 retainCount]);

  [myArr addObject: myStr1];
  [myArr addObject: myStr2]; 
  [myArr addObject: myStr3];

  printf ("Retain count: myStr1: %x, myStr2: %x, myStr3: %x\n",
          [myStr1 retainCount], [myStr2 retainCount],
          [myStr3 retainCount]);

  [myStr1 retain];
  [myStr2 retain];
  [myStr3 retain];

  printf ("Retain count: myStr1: %x, myStr2: %x, myStr3: %x\n",
          [myStr1 retainCount], [myStr2 retainCount],
          [myStr3 retainCount]);

  // Bring the reference count of myStr2 and myStr3 back down to 2

  [myStr2 release];
  [myStr3 release];

  [pool release];
  return 0; 
}


					  


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint