如何在框架的类中覆盖方法(运行时) [英] How to override a method in framework's class (runtime)
问题描述
问题:
高于上述条件时,框架将缓存图像数据:
problem:
framework will cache the image data when above:
[UIImage imageNamed:]
我不希望缓存发生,所以我可以用
I don't want the caching happen,so I can replace it by
[UIImage imageOfContentOfFile:]
似乎解决了,但是在我的测试中,在xib的实例化进度中,框架使用了 imageNamed:而不是 imageOfContentOfFile .
也就是说,xib加载的图像仍被缓存.
Seems solved,but after my tests,in xib's instantiate progress, framework uses imageNamed: rather than imageOfContentOfFile.
That is, images loaded by xib still cached.
因此,我尝试覆盖UIImage的imageNamed:方法,使所有此方法都不要缓存.
So I try to override the UIImage's imageNamed: method, make all this method DO NOT CACHE.
-尝试1.类别:
@implementation UIImage (ImageNamedNoCache)
+ (UIImage *)imageNamed:(NSString *)name;
{
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:nil];
return [UIImage imageWithContentsOfFile:path];
}
@end
-result:warning.类别正在实现一种方法,该方法也将由其主类实现".
--result:warning."Category is implementing a method which will also be implemented by its primary class"
-尝试2.运行时替换方法的imp
//get super method
Method method_imageNamed = class_getClassMethod([UIImage class], @selector(imageNamed:));
//get my method
Method method_myImageNamed = class_getClassMethod([self class], @selector(myImageNamed:));
//get my imp
IMP imp_myImageNamed = method_getImplementation(method_myImageNamed);
//set super method's imp to my imp
method_setImplementation(method_imageNamed, imp_myImageNamed);
-结果这些也只能尝试在我调用 [UIImage imageNamed:]
时起作用但是xib的实例化不起作用.
--result
these too try only work when I invoke [UIImage imageNamed:]
but xib's instantiation doesn't work.
帮助我,谢谢
推荐答案
听起来像方法陷入困境.我觉得这很危险,也没有必要,但是如果您愿意的话,它是一个选择.使用风险自负.
Sounds like a job for method swizzling. I find it dangerous and unnecessary, but if you are so inclined, it is an option. Use at your own risk.
这篇关于如何在框架的类中覆盖方法(运行时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!