Is Class an object, or is it a struct?
Is Class
an 开发者_如何学编程object, or is it a struct?
Objective-C classes are considered as objects, with a few restrictions (see Objective-C Programming Language):
Class objects are thus full-fledged objects that can be dynamically typed, receive messages, and inherit methods from other classes. They’re special only in that they’re created by the compiler, lack data structures (instance variables) of their own other than those built from the class definition, and are the agents for producing instances at runtime.
Behind the scene, a class definition contains various kinds of information, much of it about instances of the class:
- The name of the class and its superclass
- A template describing a set of instance variables
- The declarations of method names and their return and argument types
- The method implementations
Officially, it's implemented as a struct, but the Objective-C runtime let's you treat a Class as an object. Cocoa with Love has a great article on how classes and meta-classes work in Objective-C.
Class
types are reference-types and struct
types are value types. Instances of class or struct types are called objects.
Class
is a type that can hold the pointer to a class object (similar to how id
is a type that can hold the pointer to any object). Class
is not the name of a class (similar to how id
is not the name of a class). The class of a class object is the metaclass of that class (will not go into that here). Class objects are first-class objects; and you can do the same things with them as regular objects. Calling a method on a class object calls a class method on that class (or some ancestor class); you can also call the instance methods of the class's root class on a class object.
精彩评论