繁体   English   中英

CategoryA应该如何覆盖categoryB方法

[英]How should CategoryA override categoryB method

AFNetworking 2.0中,在UIImageView+AFNetworking有一种方法:

+ (id <AFImageCache>)sharedImageCache

我想覆盖它并在这里返回我的自定义对象。 我也想重写AFImageCache所有方法,因此基本上我会在这里建立一个新协议。 我曾经考虑过方法混乱,但是由于缺乏经验,我不确定这是否适用于2类。 如果我的类别在AFNetworking类别之前AFNetworking ,它将仍然有效吗?

根本上,这是一种好方法吗? 我想将磁盘缓存添加到内存中,而我不知道哪种方式在代码质量方面是最干净的。

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

"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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM