gpt4 book ai didi

objective-c - 如何在没有 NSObject 的情况下在 Objective-C 中创建根对象?

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

文档说:

While not strictly a part of the language, the isa pointer is required for an object to work with the Objective-C runtime system. An object needs to be “equivalent” to a struct objc_object (defined in objc/objc.h) in whatever fields the structure defines. However, you rarely, if ever, need to create your own root object, and objects that inherit from NSObject or NSProxy automatically have the isa variable.

虽然这听起来不错,但我想知道如何在 Objective-C 中创建根对象?

这是为了学习目的。我只想知道这个。我真的很想看。

最佳答案

这实际上是一些从 C# 或 Java 风格语言迁移过来的人落入的“陷阱”。您在声明类时根本不指定父类(super class),即

@interface MyNewRoot {
Class isa;
}
@end

对比

@interface MyObject : NSObject {
}
@end

在 Java 或 C# 中,它们是等效的(在第一种情况下,编译器会假定 System.Object 或 java.lang.Object 是父类(super class)),但在 Objective-C 中,不会假定这样的默认值,因此一个新的根已创建。

但是,您现在要负责您的类的许多您通常认为理所当然的功能(甚至是简单的事情,例如用于分配或销毁新实例的内存管理等)。这就是你引用的评论在谈到 struct objc_object 和 isa 实例变量等时所暗示的。

关于objective-c - 如何在没有 NSObject 的情况下在 Objective-C 中创建根对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835704/

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