How Instances Are Created

Your class objects are created for you automatically as your program starts up, but instances must be created deliberately as the program runs. The entire question of where instances come from is thus crucial. Ultimately, every instance comes into existence in just one way: someone deliberately asks a class to instantiate itself. 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 to an NSString, and you get back a different, newly created NSString. After that line of code, s2 points to an NSString instance that didn’t exist beforehand.

The NSString produced by the uppercaseString method is a ready-made NSString instance. Your code didn’t say anything about instantiation; it just sent the uppercaseString message. But clearly someone said something about instantiation, because instantiation took place; this is a newly ...

Get Programming iOS 6, 3rd Edition 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.