Chapter 5. Objective-C Instances

Instances are the heart of the action in an Objective-C program. Obtaining and manipulating instances will be crucial to just about everything you do. Nearly every line of code that you write will be concerned with one or more of these activities:

  • Referring to an instance that already exists
  • Creating a new instance that didn’t exist previously
  • Assigning an instance to a variable
  • Sending a message to an instance
  • Passing an instance as an argument in a method call

How Instances Are Created

Your class objects are created for you automatically as your program starts up, but instances must be created individually as the program runs. Ultimately, every instance comes into existence in just one way: someone asks a class to instantiate itself (see Chapter 4). But there are three different ways in which this can occur: ready-made instances, instantiation from scratch, and nib-based instantiation.

Ready-Made Instances

One way to create an instance is indirectly, by calling code that does the instantiation for you. You can think of an instance obtained in this indirect manner as a “ready-made instance.” (That’s my made-up phrase, not an official technical term.) Consider this simple code:

NSString* s2 = [s uppercaseString];

The documentation for the NSString instance method uppercaseString says that it returns “a string with each character from the receiver changed to its corresponding uppercase value.” In other words, you send the uppercaseString message ...

Get iOS 7 Programming Fundamentals now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.