在AFNetworking
2.0中,在UIImageView+AFNetworking
中有一种方法:
+ (id <AFImageCache>)sharedImageCache
我想覆盖它并返回我的自定义对象。我还要覆盖AFImageCache
中的所有方法,所以基本上我在这里制作一个新的协议。我已经考虑过方法调整,但是由于缺乏经验,我不确定它是否适用于2类。如果我的类别在AFNetworking
类别之前加载,它仍然有效吗?
总之,这种方法是好的吗?我想将光盘缓存添加到内存中,我想知道哪种方式在代码质量方面最干净。
答案 0 :(得分:1)
不要使用Categories来覆盖方法。根据文件
"If the name of a method declared in a category is the same as a
method in the original class, or a method in another category on
the same class (or even a superclass), the behavior is undefined
as to which method implementation is used at runtime. "
请参阅&#34;避免类别方法名称冲突&#34; - &GT; https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf
改为子类并覆盖该方法并使用子类?
分析您的场景,进行方法调配是有意义的。 注意:确保yourCache的行为与sharedImageCache相同,否则会导致崩溃。
@implementation UIImageView (Swizzling)
+ (void)load {
static dispatch_once_t token;
dispatch_once(&token, ^{
Class myClass = [self class];
Method originalMethod = class_getInstanceMethod(myClass, @selector(sharedImageCache));
Method newMethod = class_getInstanceMethod(myClass, @selector(NewSharedImageCache:));
method_exchangeImplementations(originalMethod, newMethod);
});
}
//This is just for sample. you can create your buffer in your own way
static id <yourCache> yourBuffer;
+ (id <yourCache>)NewSharedImageCache
{
return yourBuffer;
}
@end