开发者

Message Forwarding in Objective C

开发者 https://www.devze.com 2022-12-13 23:25 出处:网络
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 b开发者_运维问

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 b开发者_运维问答est as an introduction.


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.


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 custom NSManagedObject subclasses for every entity. This sort of reminds me of method_missing in Ruby.

0

精彩评论

暂无评论...
验证码 换一张
取 消