Chapter 5. Objective-C Instances
Instances are the heart of the action in an Objective-C program. Most of the methods you’ll define when creating your own classes will be instance methods; most of the messages you’ll send in your code will call instance methods. This chapter describes how instances come into existence and how they work.
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 turns to a class and ask that 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.) For example, consider this simple code:
NSString* s2 = [s uppercaseString];
The documentation for the NSString instance method uppercaseString
says that it returns an NSString*
that is “an uppercased representation of the receiver.” 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 ...
Get Programming iOS 5, 2nd 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.