求iOS 两个View的最近公共父类
分析:
1、iOS的集成关系里:所有的类的终极父类:NSObject;
2、iOS 是单继承;
3、算法解析:本质是数据结构中的二叉树,查找一个普通二叉树中两个节点最近的公共祖先问题;
代码:
#warning 求两个View的最近公共父类
- (NSArray *)superClasses:(Class)cls{
if (cls == nil) {
return @[];
}
NSMutableArray *res = [NSMutableArray arrayWithCapacity:10];
while (cls != nil) {
[res addObject:cls];
cls = [cls superclass];
}
return [res copy];
}
- (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];
}
调用:
NSArray *result = [self commonSuperClsss:[UITextField class] withClssB:[UITextView class]];
NSLog(@"== %@", result);
结果:
2021-05-16 13:13:51.449045+0800 TestLearn[22891:1260669] == UIView
网友评论