0

AFNetworking2.0 中,UIImageView+AFNetworking有一个方法:

+ (id <AFImageCache>)sharedImageCache

我想覆盖它并在这里返回我的自定义对象。我还想覆盖 中的所有方法AFImageCache,所以基本上我会在这里创建一个新协议。我考虑过方法调配,但是由于缺乏经验,我不确定它是否适用于 2 个类别。如果我的类别在AFNetworking类别之前加载,它仍然可以工作吗?

这种方法到底好不好?我想将磁盘缓存添加到内存中,我想知道在代码质量方面哪种方式最干净。

4

1 回答 1

1

不要使用类别来覆盖方法。根据文档

"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. "

请参阅“避免类别方法名称冲突”中的文档-> 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
于 2014-05-28T17:34:08.897 回答