1.简单 for
循环
- (Class)commonClass1:(Class)classA andClass:(Class)classB {
NSArray *arr1 = [self superClasses:classA];
NSArray *arr2 = [self superClasses:classB];
for (NSUInteger i = 0; i < arr1.count; ++i) {
Class targetClass = arr1[i];
for (NSUInteger j = 0; j < arr2.count; ++j) {
if (targetClass == arr2[j]) {
return targetClass;
}
}
}
return nil;
}
//获取所有父类
- (NSArray *)superClasses:(Class)cls{
if (cls == nil) {
return @[];
}
NSMutableArray *res = [NSMutableArray array];
while (cls != nil) {
[res addObject:cls];
cls = [cls superclass];
}
return [res copy];
}
2.优化
iOS 的集成关系里:所有的类的终极父类:NSObject
,且 iOS 是单继承.
其实就相当于这两个类的继承链从 NSObject
开始向下一直是重合的,直到最后的一个公共父类才开始分开,这个最后的公共父类也是最近的公共父类,这是典型的倒 Y 字型链表组合。
- (Class)commonSuperClsss:(Class)clsA withClssB:(Class )clsB{
NSArray *clsAs = [[[self superClasses:[clsA class]] reverseObjectEnumerator] allObjects];
NSArray *clsBs = [[[self superClasses:[clsB class]] reverseObjectEnumerator] allObjects];
NSInteger count = clsAs.count > clsBs.count ? clsBs.count : clsAs.count;
int idx = -1;
for (int i = 0; i < count; i ++) {
idx = i;
if (clsAs[i] != clsBs[i]) {
break;
}
}
idx = idx == 0 ? 0 : idx - 1;
return clsAs[idx];
}