如何在没有 NSObject 的情况下在 Objective-C 中创建根对象? [英] How to create a root object in Objective-C without NSObject?

查看:50
本文介绍了如何在没有 NSObject 的情况下在 Objective-C 中创建根对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说:

虽然不是严格意义上的一部分语言,需要 isa 指针一个对象与Objective-C 运行时系统.一个东西需要等价于"一个结构体objc_object(在 objc/objc.h 中定义)在任何领域的结构定义.然而,你很少,如果有的话,需要创建自己的根对象,和从 NSObject 继承的对象或 NSProxy 自动拥有 isa变量.

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 中创建根对象?

While that sounds nice, I wonder how an root object would be created in Objective-C anyways?

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

This is for learning purposes. I just want to know this. I'd really like to see it.

推荐答案

这实际上是一些从 C# 或 Java 风格语言迁移的人落入的陷阱".您在声明类时根本不指定超类,即

It's actually a "trap" some people migrating from C# or Java style languages fall into. You simply don't specify a superclass when declaring your class i.e.

@interface MyNewRoot {
Class isa;
}
@end

对比

@interface MyObject : NSObject {
}
@end

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

In Java or C# these would be equivalent (in the first case the compiler would assume System.Object or java.lang.Object was the superclass), but in Objective-C no such default will be assumed, and hence a new root is created.

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

However you're now responsible for a number of features for your class that you typically take for granted (even simple things like memory management for allocating or destorying new instances etc). This is what the comment you quoted hints at when it talks about struct objc_object and the isa instance variable etc.

这篇关于如何在没有 NSObject 的情况下在 Objective-C 中创建根对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆