在目标C中如何实现类别? [英] How are categories implemented in Objective C?

查看:82
本文介绍了在目标C中如何实现类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用类别作为程序员,但我很好奇它们的实现方式。编译器是否将它们编译为对 class_replaceMethod 来自静态初始化程序?谢谢。

I know how to use categories as a programmer, but I'm curious how they are implemented. Does the compiler compile them into calls to class_replaceMethod from a static initializer? Thanks.

推荐答案

关于主题的新答案。

每个类都有方法列表,在执行方法查找时,从头到尾扫描方法列表。如果找不到方法,则扫描超类列表,以此类推,直到到达根类为止。找到的方法将被缓存,以便下次更快地查找。

Each class has a list of methods, when doing a method lookup the method list is scanned from beginning to end. If no method is found the superclass' list is scanned, etc. until reaching the root class. Found methods are cached for faster lookup next time.

将类别加载到类时,类别方法列表被放在之前,并刷新缓存。由于列表是按顺序搜索的,因此这意味着将在下一次搜索的原始方法之前找到类别方法。

When loading a category onto a class the categories method list is prepended to the existing list, and caches are flushed. Since the list is searched sequentially this means that the categories method will be found before the original method on next search.

此类别设置为首次访问该类时,根据静态数据懒惰地完成操作。如果加载带有可执行代码的捆绑包,则可以重新执行。

This setup of categories is done lazily, from static data, when the class is first accessed. And can be re-done if loading a bundle with executable code.

简而言之,它的级别比 class_replaceMethod()低。

In short it is a bit more low level than class_replaceMethod().

这篇关于在目标C中如何实现类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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