天天看点

Category 高级使用

1、分类会覆盖本类的方法?

1. category的方法没有“完全替换掉”原来类已经有的方法,也就是说如果category和原来类都有methodA,那么category附加完成之后,类的方法列表里会有两个methodA 2. category的方法被放到了新方法列表的前面,而原来类的方法被放到了新方法列表的后面,这也就是我们平常所说的category的方法会“覆盖”掉原来类的同名方法,这是因为运行时在查找方法的时候是顺着方法列表的顺序查找的,它只要一找到对应名字的方法,就会罢休^_^,殊不知后面可能还有一样名字的方法

2、如何调用被分类覆盖的方法?  + (void)useClassMethodInsteadCayegoryMethod: (SEL)seletor {    if (self) {    unsigned int methodCount;    Method *methodList = class_copyMethodList([self class], &methodCount);    IMP lastImp = NULL;    SEL lastSel = NULL;     for (NSInteger i = 0; i < methodCount; i++) {    Method method = methodList[i];    NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(method)) encoding:NSUTF8StringEncoding];    NSString *selectorName = NSStringFromSelector(seletor);    if ([selectorName isEqualToString:methodName]) {    lastImp = method_getImplementation(method);    lastSel = method_getName(method);   }    }    typedef void (*fn)(id,SEL);    if (lastImp != NULL) {    fn f = (fn)lastImp;    f(self,lastSel);    }    free(methodList);    }}

继续阅读