Are classes objects in Objective-C?

允我心安 提交于 2019-12-27 20:12:12

问题


okay, so I understand that an object is an instance of a class that must be allocated and initialized, but are classes themselves objects?

I know when you create a new class it is an instance of something else, like NSObject. So, if this makes it a class, then objects can hold not only variables and methods, but other objects as well, right?

Sorry, this is probably really basic, but I am reading two books about cocoa and xcode and this point is a little unclear (probably because of my lack of experience in other languages).


回答1:


Here is a pretty good explanation of the matter by Greg Parker

Quoting:

[...] Each Objective-C class is also an object. It has an isa pointer and other data, and can respond to selectors. When you call a "class method" like [NSObject alloc], you are actually sending a message to that class object.

Since a class is an object, it must be an instance of some other class: a metaclass. The metaclass is the description of the class object, just like the class is the description of ordinary instances. In particular, the metaclass's method list is the class methods: the selectors that the class object responds to. When you send a message to a class - an instance of a metaclass - objc_msgSend() looks through the method list of the metaclass (and its superclasses, if any) to decide what method to call. Class methods are described by the metaclass on behalf of the class object, just like instance methods are described by the class on behalf of the instance objects.

What about the metaclass? Is it metaclasses all the way down? No. A metaclass is an instance of the root class's metaclass; the root metaclass is itself an instance of the root metaclass. The isa chain ends in a cycle here: instance to class to metaclass to root metaclass to itself. The behavior of metaclass isa pointers rarely matters, since in the real world nobody sends messages to metaclass objects. [...]

Further interesting reads:

Understanding the Objective-C Runtime by Colin Wheeler
(search for paragraph titled "So Classes define objects…")

What is a meta-class in Objective-C? by Matt Gallagher



来源:https://stackoverflow.com/questions/5773054/are-classes-objects-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!