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 18. Copying Objects > Shallow Versus Deep Copying

Shallow Versus Deep Copying

Program 18.1 fills the elements of dataArray with immutable strings (recall that constant string objects are immutable). In Program 18.2, you’ll fill it with mutable strings instead so that you can change one of the strings in the array. Take a look at Program 18.2 and see whether you understand its output.

Program 18.2.

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

int main (int argc, char *argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSMutableArray    *dataArray = [NSMutableArray arrayWithObjects:
      [NSMutableString stringWithString: @"one"],
      [NSMutableString stringWithString: @"two"],
      [NSMutableString stringWithString: @"three"],
      nil
   ];
   NSMutableArray  *dataArray2;
   NSMutableString *mStr;

   NSLog (@"dataArray:  ");
   for ( NSString *elem in dataArray )
      NSLog (@" %@", elem);

   // make a copy, then change one of the strings

   dataArray2 = [dataArray mutableCopy];

   mStr = [dataArray objectAtIndex: 0];
   [mStr appendString: @"ONE"];

   NSLog (@"dataArray:  ");
   for ( NSString *elem in dataArray )
      NSLog (@" %@", elem);

   NSLog (@"dataArray2:  ");
   for ( NSString *elem in dataArray2 )
      NSLog (@" %@", elem);

   [dataArray2 release];
   [pool drain];
   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 Trial


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