求iOS 兩個View的最近公共父類
分析:
1、iOS的集成關系里:所有的類的終極父類:NSObject谅海;
2脸哀、iOS 是單繼承;
3扭吁、算法解析:本質是數(shù)據(jù)結構中的二叉樹撞蜂,查找一個普通二叉樹中兩個節(jié)點最近的公共祖先問題;
代碼:
#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