如何在运行时替换 Objective-C 2.0 类方法实现 [英] How to replace Objective-C 2.0 class method implementation in runtime

查看:58
本文介绍了如何在运行时替换 Objective-C 2.0 类方法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用过 class_replaceMethod 函数,它适用于实例方法,但它不适用于类方法替换.

I have used class_replaceMethod function and it works good with instance methods, but I it doesn't work with class method replacement.

有没有人知道为什么以及我应该怎么做来替换类方法的实现?

Has anybody idea why and what should I do to replace class method implementation?

推荐答案

如果你有一个 Class(我们称之为 MyClass),那么你必须得到它的元类对类方法进行操作.

If you have a Class (we'll call it MyClass), then you have to get its meta class to operate on class methods.

换句话说:

Class myClass = [MyClass class];
unsigned int numInstanceMethods = 0;
Method * instanceMethods = class_copyMethodList(myClass, &numInstanceMethods);
//instanceMethods is an array of all instance methods for MyClass

Class myMetaClass = objc_getMetaClass(class_getName(myClass));
unsigned int numClassMethods = 0;
Method * classMethods = class_copyMethodList(myMetaClass, &numClassMethods);
//classMethods is an array of all class methods for MyClass

基本上,类用于操作实例级的东西,而元类用于操作类级的东西.

Basically, the class is for operating on instance-level stuff, and the meta class is for operating on class-level stuff.

希望这足以帮助您找出从这里开始的地方.:)

Hopefully this is enough to help you figure out where to go from here. :)

更多有用的信息:http://www.sealiesoftware.com/blog/archive/2009/04/14/objc_explain_Classes_and_metaclasses.html

这篇关于如何在运行时替换 Objective-C 2.0 类方法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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