gpt4 book ai didi

objective-c - Objective-C 中的类是对象吗?

转载 作者:太空狗 更新时间:2023-10-30 03:11:30 26 4
gpt4 key购买 nike

好的,所以我明白对象是必须分配和初始化的类的实例,但是类本身是对象吗?

我知道当你创建一个新类时,它是其他东西的实例,比如 NSObject。所以,如果这使它成为一个类,那么对象不仅可以包含变量和方法,还可以包含其他对象,对吧?

抱歉,这可能真的很基础,但我正在阅读两本关于 cocoa 和 xcode 的书,这一点有点不清楚(可能是因为我缺乏其他语言的经验)。

最佳答案

Here Greg Parker 对此事的解释非常好

引用:

[...] 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. [...]

更多有趣的读物:

Understanding the Objective-C Runtime通过科林·惠勒
(搜索标题为“So Classes define objects…”的段落)

What is a meta-class in Objective-C?作者:马特·加拉格尔

关于objective-c - Objective-C 中的类是对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5773054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com