开发者

Which object called another object's method in Obj-C

开发者 https://www.devze.com 2022-12-26 23:24 出处:网络
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.

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.


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.


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.

0

精彩评论

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