如何在 Objective-C 中动态添加方法到类中?
我知道 Objective-C 相对于 C++ 的一个主要优点是它能够向对象发送消息而不是调用其方法。其次,您可以动态地向对象添加方法。
假设这是我的对象:
@interface MyClass : NSObject
{}
- sayHello;
@end
我知道即使没有定义 - sayGoodbye
,下面的代码也能工作,但是有人可以完成这段代码并演示 Objective-C 如何在运行时向对象添加方法吗?
MyClass* o = [[MyClass alloc] init];
[o sayHello ];
[o sayGoodbye];
[o release ];
I understand a major advantage of Objective-C over C++ is its ability to send messages to objects instead of calling its methods. Secondly you are allowed to dynamically add a method to objects.
Suppose this is my object:
@interface MyClass : NSObject
{}
- sayHello;
@end
I know my code below will work even if - sayGoodbye
isn't defined, but can someone finish this code and demonstrate how Objective-C can add methods to objects at runtime?
MyClass* o = [[MyClass alloc] init];
[o sayHello ];
[o sayGoodbye];
[o release ];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Objective C 运行时参考是您需要的:
Objective-C 运行时参考
特别查看以下方法:
class_addMethod
The objective c runtime reference is what you need here:
Objective-C Runtime Reference
in particular look at the following method:
class_addMethod