动态打字,Objective-C,它是如何工作的? [英] Dynamic typing, Objective-C, how does it work?

查看:163
本文介绍了动态打字,Objective-C,它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective-C中的动态打字如何工作感兴趣。我一直在研究id类型,我知道它的作用和使用方法,但我很好奇...这样的功能如何在引擎盖下实现?

I'm interested in how does dynamic typing in Objective-C work. I've been studying the "id" type, I know what it does and how to use it, but I'm curious... How does such functionality get implemented under the hood?

只有在运行时,您无法在编译期间确定/解析任何内容。我想这可以简单地指向内存中某些对象的第一个字节,但是如何存储类签名?它如何知道它目前指向什么,以及如何为尖锐对象的类实现各种getter?

You cannot determine/resolve anything during compile time, only during runtime. I guess it can simply just point to the first byte of some object in memory, but how is the class signature stored? How does it know what is it currently pointing towards and how does it implement various getters for the class of the pointed object?

推荐答案

可以这么说,所有Objective-C对象都是C结构体,指向指向Class对象的指针,表示它们的类型。一个 id 是一个指向最基本的这样的结构体的指针,看起来像这样:

"Under the hood", so to speak, all Objective-C objects are C structs with a pointer to the Class object that represents their type. An id is a pointer to the most basic such struct, which looks something like this:

struct objc_object {
    Class isa;
}

id 被处理特别是编译器,因为编译器不会给你任何警告,即对象可能没有响应任何选择器,就像使用更强类型的变量一样。

id is treated specially by the compiler, in that the compiler doesn't give you any warning that the object may not respond to any selector as it does when you use a more strongly typed variable.

当您调用任何对象的方法时,就会发现指向Class对象的 isa 指针,并查找该Class对象以找到该方法的选择器的实现函数你试图打电话。

When you call a method on any object, it follows that isa pointer to the Class object and looks in that Class object to find the implementation function for the selector of the method you tried to call.

这篇关于动态打字,Objective-C,它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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