Objective C 中的消息转发
Can anyone give a brief explanation of how to use message forwarding?
Links
- Apple documentation: Apple documentation tends to be good as a reference, but lengthy enough to not be the best as an introduction.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单委托模式:您的对象响应消息 aMethod,然后它通过发送 [otherObject respondsToSelector:@selector(aMethod)] 来检查其他对象是否响应消息 aMethod,该对象返回一个 bool。如果 otherObject 这样做了,那么您就可以发送消息了。
更具技术性的 NSInitation 方法:如果向您的对象发送一条它无法响应的消息 (crazyMethodName),则在您的对象上调用forwardInitation。 NSObject 的forwardIncation 的默认实现只调用doesNotRecognizeSelector,因为你的对象无法识别选择器。您可以通过检查另一个对象是否响应调用的选择器并在另一个对象上调用该调用(如果是)来覆盖forwardInitation的默认实现。
Simple delegation pattern: your object responds to the message aMethod, then it check if some other object responds to the message aMethod by sending [otherObject respondsToSelector:@selector(aMethod)], which returns a bool. If otherObject does, you're all clear to send the message.
More technical goodness NSInvocation method: if your object is sent a message it can't respond to (crazyMethodName), then forwardInvocation is called on your object. The default implementation of forwardInvocation for NSObject just calls doesNotRecognizeSelector because, well, your object doesn't recognize the selector. You can override the default implementation of forwardInvocation by checking if another object responds to the selector of the invocation, and invoking that invocation on the other object if so.
消息转发的一个常见用途是让一个类充当其他类的代理:您将消息发送到此 NSProxy 子类的实例,然后它将它分派到它认为合适的任何类或对象。
消息转发实际上只允许类接收它本来不接受的消息:您甚至可以使用它动态创建动态方法。它的一个应用是 NSManagedObject 类别,它允许您在方法调用中访问 Core Data 属性,而无需为每个实体编写自定义的 NSManagedObject 子类。这让我想起了 Ruby 中的
method_missing
。A common use of message forwarding is to make a class act as a proxy for other classes: you send a message to an instance of this
NSProxy
subclass, and it dispatches it to whichever class or object it deems fit.Message forwarding really just allows a class to receive messages that it was not designed to accept: you can even use it to dynamically create methods on the fly. An application of this would be a
NSManagedObject
category that let you access Core Data properties in method calls, without writing customNSManagedObject
subclasses for every entity. This sort of reminds me ofmethod_missing
in Ruby.