这题可以作为面试题,手写代码。
我曾经被tx的人面过。


- (MAS_VIEW *)mas_commonSuperviewOfViews
{
    MAS_VIEW *commonSuperview = nil;
    MAS_VIEW *previousView = nil;
    for (id object in self) {
        if ([object isKindOfClass:[MAS_VIEW class]]) {
            MAS_VIEW *view = (MAS_VIEW *)object;
            if (previousView) {
                commonSuperview = [view mas_closestCommonSuperview:commonSuperview];//下面有解释这个方法。
            } else {
                commonSuperview = view;//这里会先执行,保证了上面找寻最近公共父视图时不为空
            }
            previousView = view;
        }
//递归完后,commonSuperView 为 内中的所有公共父视图
    }
    NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy.");
    return commonSuperview;
}

上面要注意的是:MAS_VIEW 是根据操作系统定义的视图基类
写sdk 或 跨平台的时候可以用到这种写法:

#if TARGET_OS_IPHONE || TARGET_OS_TV
    #import <UIKit/UIKit.h>
    #define MAS_VIEW UIView
    #define MAS_VIEW_CONTROLLER UIViewController
    #define MASEdgeInsets UIEdgeInsets
 ...
#elif TARGET_OS_MAC
    #import <AppKit/AppKit.h>
    #define MAS_VIEW NSView
    #define MASEdgeInsets NSEdgeInsets
...
#endif

上面有个找寻共同最近父类视图的方法:

//这个方法在View+ 拓展里
- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view {
    MAS_VIEW *closestCommonSuperview = nil;

    MAS_VIEW *secondViewSuperview = view;
    while (!closestCommonSuperview && secondViewSuperview) {//没找到commonSuperview时会一直为真
        MAS_VIEW *firstViewSuperview = self;
        while (!closestCommonSuperview && firstViewSuperview) {//没找到时一直为真
            if (secondViewSuperview == firstViewSuperview) {//如果两者为同一个,则为找到。
                closestCommonSuperview = secondViewSuperview;
            }
            firstViewSuperview = firstViewSuperview.superview;// 不断递归self的父视图
        }
        secondViewSuperview = secondViewSuperview.superview;//如果上面内层没找到父视图,就不断递归view的父视图。
    }
//考虑到最终是能找到的,所以,这里最终会有返回。
    return closestCommonSuperview;
}

最后,我为何写这个, 上面的代码出现在
NSArray+MASAdditions
这是一个可以对数组视图进行设置的,类似于UIStack的效果,你说神奇不,有用不。

感谢,你的阅读。分析完毕。