IOS4 note 九

IOS4 note 9

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.

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 class] returns the actual class object

To supply this as an argument, you’d need to obtain a class object formally. Take, for example, introspection on an object to inquire what its class is. The isKindOfClass: instance method is declared like this:

- (BOOL)isKindOfClass:(Class)aClass

So that means you could call it like this:

if ([someObject isKindOfClass: [MyClass class]]) // ...

 

A class object is not an instance, but it is definitely a full-fledged object. Therefore, a class object can be used wherever an object can be used. For example, it can be assigned to a variable of type id:

id classObject = [MyClass class];

You could then call a class method by sending a message to that object, because it is the class object:

id classObject = [MyClass class];

[classObject someClassMethod];

All class objects are also members of the Class class, so you could say this:

Class classObject = [MyClass class];

[classObject someClassMethod];