The Secret Life of Classes
A class method may be called by sending a message directly to the name of a class. For example, the familyNames class method of UIFont that I mentioned a moment ago might be called like this:
NSArray* fams = [UIFont familyNames];
Clearly, this is possible because a class is an object (Chapter 2), and the name of the class here represents that object.
You don’t have to do anything to create a class object. One class object for every class your program defines is created for you automatically as the program starts up. (This includes the classes your program imports, so there’s a MyClass class object because you defined MyClass, and there’s an NSString class object because you imported UIKit.h and the whole Cocoa framework.) It is to this class object that you’re referring when you send a message to the name of the class.
Your ability to send a message directly to the bare name of a class is due to a kind of syntactic shorthand. You can use the bare class name only in two ways (and we already know about both of them):
- To send a message to
-
In the expression
[UIFont familyNames], the bare nameUIFontis sent thefamilyNamesmessage. - To specify an instance type
-
In the expression
NSString*, the bare nameNSStringis followed by an asterisk to signify a pointer to an instance of this class.
Otherwise, to speak of a class object, you need to obtain that object formally. One way to do this is to send the class message to a class or instance. For example, [MyClass ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access