Objective-C 运行时:如何从类中删除方法?

发布于 2024-12-13 00:37:10 字数 300 浏览 2 评论 0原文

Objective-C 运行时参考,我看到 class_addMethod 但没有看到 class_removeMethod。如何动态删除方法?

另外,class_addMethod 是添加实例方法还是类方法?

In the Objective-C Runtime Reference, I see class_addMethod but not class_removeMethod. How do I dynamically remove a method?

Also, does class_addMethod add an instance method or a class method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱娆 2024-12-20 00:37:10

正如 Inerdial 在他的评论中提到的,主要问题(如何在运行时从类中删除方法?)在某种程度上得到了详尽的回答 此处

马特迪帕斯夸莱也问:

另外,class_addMethod 是添加实例方法还是类方法?

惯性再次正确:

class_addMethod 添加实例方法,要添加类方法,需要在类的类中添加实例方法。

给定一个 c,我们可以得到它作为实例的类(称为它的“元类”),就像

Class metac = object_getClass(c);

然后“向 c 添加一个类方法”一样,我们添加使用 class_addMethod 的 metac 方法。

例如,如果我们已经在其他地方定义了,

id myClassMethodImplementation(id self, SEL _cmd) {
    //implementation
}

那么我们可以向 c 添加一个类方法,如下所示:

BOOL success = class_addMethod(metac, @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

或者等效地,

BOOL success = class_addMethod(object_getClass(c), @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

为了简单地将这个相同的方法添加为 c 上的实例方法,我们只需编写

BOOL success = class_addMethod(c, @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

引用:
1. Objective-C 运行时参考 2.Objective-C 运行时编程指南 - 类型编码 3.Cocoa with Love - 什么是 Objective 中的元类-C?

As Inerdial mentioned in his comment, the main question (How can a method be removed from a class at runtime?) is somewhat exhaustively answered here.

MattDiPasquale asks as well:

Also, does class_addMethod add an instance method or a class method?

Inerdial is correct again:

class_addMethod adds an instance method, and that to add a class method, you need to add an instance method to the class' class.

Given a Class c, we can get our hands on the class of which it is an instance (known as its "metaclass") as simply as

Class metac = object_getClass(c);

To then "add a class method" to c, we add a method to metac using class_addMethod.

If, for example, elsewhere we have already defined

id myClassMethodImplementation(id self, SEL _cmd) {
    //implementation
}

We can then add a class method to c as follows:

BOOL success = class_addMethod(metac, @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

or equivalently

BOOL success = class_addMethod(object_getClass(c), @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

To simply add this same method as an instance method on c, we simply write

BOOL success = class_addMethod(c, @selector(myClassMethod), (IMP)myClassMethodImplementation, "@@:");

References:
1. Objective-C Runtime Reference 2. Objective-C Runtime Programming Guide - Type Encodings 3. Cocoa with Love - What is a meta-class in Objective-C?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文