Objective-C,我如何在另一个类中连接一个方法 [英] Objective-C, how can i hook up a method in another class

查看:59
本文介绍了Objective-C,我如何在另一个类中连接一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C 将其所有方法保存在一个巨大的哈希表中 - 所以难道不应该修补这个表并用我自己的修补方法(然后调用原始方法)替换现有方法吗?

Objective-C keeps all its methods in a huge hashtable - so shouldn't it possible to patch this table and replace an existing method with my own patched method (which then calls the original)?

我需要一种方法来连接窗口中的 NSWindow KeyUp 方法,因为它已经创建,我无法子类化该方法.

I need a way to hook up the NSWindow KeyUp method in a window which i can't subclass cause it's already created.

我需要一些代码或至少一些可以用于进一步搜索的关键字.

I need some code or at least some keywords i can use for further searching.

推荐答案

当然有可能.事实上,您甚至不需要查看哈希表 - 有用于此的标准 API.

Of course it is possible. In fact, you don't even need to look into the hash table — there's standard API for this.

例如:

typedef void (*NSWindow_keyUp__IMP)(NSWindow* self, SEL _cmd, NSEvent* evt);
static NSWindow_keyUp__IMP original_NSWindow_keyUp_;

void replaced_NSWindow_keyUp_(NSWindow* self, SEL _cmd, NSEvent* evt) {
  NSLog(@"Entering keyUp:. self = %@, event = %@", self, evt);
  original_NSWindow_keyUp_(self, _cmd, evt);
  NSLog(@"Leaving keyUp:. self = %@, event = %@", self, evt);
}

...

Method m = class_getInstanceMethod([NSWindow class], @selector(keyUp:));
original_NSWindow_keyUp_ = method_setImplementation(m, replaced_NSWindow_keyUp_);

这篇关于Objective-C,我如何在另一个类中连接一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆