gpt4 book ai didi

objective-c - 在Cocoa中,Class类型是如何定义的?

转载 作者:行者123 更新时间:2023-12-03 16:24:00 24 4
gpt4 key购买 nike

来自“objc.h”:

typedef struct objc_class *Class;

但是在“runtime.h”中:

struct objc_class {
Class isa;

#if !__OBJC2__
Class super_class OBJC2_UNAVAILABLE;
const char *name OBJC2_UNAVAILABLE;
long version OBJC2_UNAVAILABLE;
long info OBJC2_UNAVAILABLE;
long instance_size OBJC2_UNAVAILABLE;
struct objc_ivar_list *ivars OBJC2_UNAVAILABLE;
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_protocol_list *protocols OBJC2_UNAVAILABLE;
#endif

} OBJC2_UNAVAILABLE;
/* Use `Class` instead of `struct objc_class *` */

到底是什么?

最佳答案

typedef struct objc_class *Class;

^ 这是一个 objc_class 指针的前向声明。它给它起了一个好记的名字Class

现在让我们看一下 objc_class 结构:(删除 Objective-C 2.0 检查以缩短时间)

struct objc_class {
Class isa;
};
//This is really saying
struct objc_class {
struct objc_class *isa;
};

现在我们有一个指向它自己类型的结构。但你为什么这么问?

取自 Inside the Objective-C Runtime, Part 2

The Class pointed to by the Class' isa (the Class' Class) contains the Class' class methods in its objc_method_list. Got that? The terminology used in the runtime is that while an object's isa points to its Class, a Class's isa points to the object's "meta Class".

So what about a meta Class' isa pointer? Well, that points to the root class of the hierarchy (NSObject in most cases). (In the Foundation framework each meta class of a subclass of NSObject "isa" instance of NSObject.) And yes, by the way, NSObject's meta Class' isa points back to the same struct -- it's a circular reference so no Class' isa is ever NULL.

<小时/>

因此,根据该描述,当您创建一个继承自 NSObject 的类时,您将拥有一个 isa ,它指向其类类型,该类类型指向其元类,该元类又指向其元类。根类 (NSObject) 包含对其自身的循环引用。这解释了它的原因requires two steps to determine if an object is an instance or a class .

假设您创建以下类:

@interface MyClass : NSObject
@end
@implementation MyClass
@end


如果您能够*遍历 isa 指针,您将得到以下结果:
*您不能,因为 isa 受到保护。请参阅下面的 Cocoa with Love 帖子,了解如何创建您自己的实现。

Class c = myClassInstance->isa; //This would be the MyClass
c = c->isa; //This would be MyClass' meta class
c = c->isa; //This would be NSObjects meta class
c = c->isa; //This going forward would still be the NSObjects meta class
...

一旦c == c->isa,您就会知道您位于根对象。请记住,Objective-C 是 C 的超集,它本身不具有面向对象的结构,例如继承。这与其他实现细节(例如指向构成完整类层次结构的父类(super class)的指针)一起允许 Objective-C 提供面向对象的功能。有关类和元类的更多信息,请参阅 Cocoa with Love 上的帖子:What is a meta-class in Objective-C?

关于objective-c - 在Cocoa中,Class类型是如何定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11265375/

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