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


1.Write a program that includes these lines of code:
NSArray *arrayOfStrings =
    [NSArray arrayWithObjects: @"", @"Objective-C", nil];

for ( NSString *string in arrayOfStrings )
    if ( [string length] == YES )
      NSLog( @"%@ has non-zero length!", string );
       NSLog( @"%@ has zero length!", string );

Verify that your program behaves badly, and then fix the program so that it works correctly.

2.Create an array of NSString objects (use whatever strings you like). Using a plain C for loop and NSArray’s objectAtIndex: method, calculate the total number of characters held by the strings in the array.
3.Rewrite your program from Exercise 2 to use a while loop and an NSEnumerator object.
4.Rewrite your program from Exercise 3 to use a for ... in loop.
5.Create the following mutable array:
NSMutableArray *animalArray =
    [NSMutableArray arrayWithObjects: @"Lion", @"Tiger",
        @"Elephant", @"Duck", @"Rhinoceros", nil];

Iterate over animalArray using a for ... in loop and try to remove all the strings that are more than five characters long from the array. Do this directly from within your for ... in loop. What happens?

6.Using the array from the previous exercise, write a program that correctly removes any string that is longer than five characters from the array. Show that your code works by logging the animalArray before and after removing the strings with a statement like:
NSLog( @"%@", [animalArray description] );

Your solution should still use a for ... in loop.

7.Create an array that holds three strings; for example:
NSArray *duckArray =

    [NSArray arrayWithObjects: @"Huey", @"Dewie",
                               @"Louie", nil];

Next, set up @try/@catch/@finally blocks. The @catch block should catch an NSException object and log the exception name and reason. The @finally block should contain a logging statement so you can tell if it has been block executed. Put another logging statement after the @try/@catch/@finally blocks.

Put a statement that accesses the array inside the @try block. Try to access the array element at index 2. Verify that the code in the @finally block is executed.

Next, change your code and attempt to access the array element at index 3. What happens?


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