Obj-C 中哪个对象调用了另一个对象的方法
我希望在 Cocoa 中编写一个插件控制器来加载包,并公开一组特定的方法供插件调用。
我的问题是:是否有可能知道有关在控制器中调用方法的对象的(任何)信息。当实例化的插件调用我的插件控制器中的方法时,我想知道哪个插件实例调用了该方法,而不必依赖插件发送指向自身的指针作为参数(我总是可以验证它们发送的指针) ,但我希望 API 方法尽可能简单)。
可能没有完美的解决方案(并且有简单的解决方法),但如果可能的话,学习一些新技巧(或为什么不可能的原因)总是好的。
提前致谢。
I am looking to write a plugin controller in Cocoa that loads bundles, and exposes a specific set of methods for the plugins to call.
My question is this: is it possible to know (any) info about the object that called a method in the controller. When an instantiated plugin calls a method in my plugin controller, I would like to know which of the plugin instances called the method, without having to rely on the plugin sending a pointer to itself as a parameter (I could always validate the pointer they send, but I want to keep the API methods as simple as possible).
There may be no perfect solution (and there are simple workarounds), but it's always good to learn some new tricks if possible (or the reasons why it's impossible).
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果不遍历堆栈,这是不可能的,甚至可能也不可能。甚至不能保证给定的消息是从方法内发送的——即使是,它也可能不是您认为的“调用者”的方法。例如,假设您的插件可以访问 Cocoa,您的控制器方法可以由 NSTimer 调用。
一般来说,这是不切实际的。实现此目的的正常方法是让对象自行传递。如果您出于安全原因尝试这样做,无论如何您都会需要一个更强大的解决方案,因为 Cocoa 的对象模型在设计时并未考虑到这一点。物体很容易谎报它们是谁、是什么。
It's not possible without walking the stack, and possibly not even then. There's not even a guarantee that a given message was sent from within a method — and even if it was, it may not be the method that you think of as being the "caller." For example, assuming your plugins have access to Cocoa, your controller methods could be called by an NSTimer.
In general, this is not practical. The normal way to accomplish this is to have objects pass themselves around. If you're trying to do this for security reasons, you'll want a much more robust solution anyway, because Cocoa's object model was not designed with that in mind. It's way too easy for objects to lie about who and what they are.
好吧,您可以抛出一个异常,捕获它并检查它的堆栈跟踪。
当然,假设 Objective-C 支持异常。
Well, you could throw an exception, catch it and examine its stacktrace.
Assuming that Objective-C supports exceptions, of course.
通常的做法是发送对调用对象的引用。作为替代方案,您可以让主机代码提供一个代理对象以供插件与之通信。加载每个插件时,为每个插件创建一个新的代理对象以进行通信。
Sending a reference to the calling object is how this is usually done. As an alternative, you could have your host code provide a proxy object for plugins to talk to. As each plugin is loaded, create a new proxy object for each to talk to.