> For the complete documentation index, see [llms.txt](https://yongpenglovemimi123.gitbook.io/henry/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yongpenglovemimi123.gitbook.io/henry/objectivec/xiao-xi-zhuan-fa.md).

# 消息转发

> Xcode11.1 Demo: <https://github.com/zColdWater/MsgForwardDemo/tree/master>

## 前言

开发 iOS 应用的小伙伴对消息转发机制肯定是再熟悉不过了，尤其是之前 `OC` 语言的年代。 下面就好好整理下消息转发。

特意为文章写了 [Demo](https://github.com/zColdWater/MsgForwardDemo/tree/master)，更好的去理解。

## 消息转发流程

消息转发流程的触发是： 调用一个没有实现的方法系统 SDK 就会触发消息转发机制。

消息转发的流程是： ![](https://raw.githubusercontent.com/zColdWater/Resources/master/Images/msgforward1.png)

## 补充

`_objc_msgForward` 是 `IMP` 类型的也就是函数实现，它是用于消息转发的，当像一个对象发送消息，但他没有实现的时候，`_objc_msgForward` 会尝试做消息转发。

其实 `Aspect` 就是利用替换函数实现成 `_objc_msgForward` 来触发的消息转发流程，而实现的，有兴趣的童鞋可以找找我的关于 Aspect 的文章。

## 总结

了解消息转发机制可以更好的帮我们做一些很不可思议的事情，比如 `Aspect` 等库的实现原理都用到了消息转发。

本文参考： <http://www.cocoachina.com/articles/12013>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yongpenglovemimi123.gitbook.io/henry/objectivec/xiao-xi-zhuan-fa.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
