Cocoa,NSProxy,如何接管对象中的方法?
我需要用我自己的实现替换对象中的方法。例如,
Person *p; // some object
NSMutableArray *array = [NSMutableArray array];
[array addObject: p];
如何用我自己的方法替换 addObject?
换句话说,有没有办法用另一个实现替换 SPECIFIC 对象的 addObject:
实现?
我一直在玩 NSProxy
但不知道我应该做什么。
任何帮助将不胜感激。
谢谢
I need to replace a method in an object with my own implementation. For example,
Person *p; // some object
NSMutableArray *array = [NSMutableArray array];
[array addObject: p];
How can I replace addObject with a method of my own?
In other words, is there a way to replace the implementation of addObject:
of a SPECIFIC object with another implementation?
I have been playing around with NSProxy
but couldnt find out what I should do.
Any help will be highly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使该对象成为具有不同方法实现的不同类的实例。
Make that object an instance of a different class with a different implementation for the method.
您可以使用类别来覆盖
NSMutableArray
的:addObject
方法。有关详细信息,请参阅学习 Objective-C 教程(第 11 节)。You could use a category to override the
:addObject
method ofNSMutableArray
. See the Learn Objective-C tutorial (section 11) for more information.您可以使用方法调配方法来替换方法运行时。实际上有一个像你一样的问题,我认为 finsl 解决方案也应该适合你 - Method swizzling for NSArray
You can use method swizzling approach for replacing methods runtime. There was actually a question as yours on SO, I think the finsl solution should work for you also - Method swizzling for NSArray