是否有视图控制器层次结构的recursiveDescription方法?

jrt*_*ton 26 objective-c uiviewcontroller ios

recursiveDescription在调试视图层次结构时非常有用.查看控制器层次结构也非常重要,是否有相应的内容?

jar*_*ora 36

为了简明扼要地回答,我在Xcode的调试器控制台中使用下面的命令来打印视图控制器层次结构:

po [[[UIWindow keyWindow] rootViewController] _printHierarchy]
Run Code Online (Sandbox Code Playgroud)

PS仅适用于ios8及更高版本,仅用于调试目的.

链接到帮助我发现这一点的文章和许多其他出色的调试技术就是这样

编辑1: 在Swift 2中,您可以通过以下方式打印层次结构:

UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_??printHierarchy")
Run Code Online (Sandbox Code Playgroud)

编辑2: 在Swift 3中,您可以通过以下方式打印层次结构:

UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
Run Code Online (Sandbox Code Playgroud)


jrt*_*ton 17

更新 - 类似的功能现在以Apple提供的形式提供_printHierarchy,因此您不再需要此类别.

现在有:

Github:视图控制器的递归描述类别.

这增加了recursiveDescription到方法UIViewController,其打印出视图控制器层次结构.非常适合检查您是否正确添加和删除子视图控制器.

代码非常简单,包含在这里以及上面的GitHub链接:

@implementation UIViewController (RecursiveDescription)

-(NSString*)recursiveDescription
{
    NSMutableString *description = [NSMutableString stringWithFormat:@"\n"];
    [self addDescriptionToString:description indentLevel:0];
    return description;
}

-(void)addDescriptionToString:(NSMutableString*)string indentLevel:(NSInteger)indentLevel
{
    NSString *padding = [@"" stringByPaddingToLength:indentLevel withString:@" " startingAtIndex:0];
    [string appendString:padding];
    [string appendFormat:@"%@, %@",[self debugDescription],NSStringFromCGRect(self.view.frame)];

    for (UIViewController *childController in self.childViewControllers)
    {
        [string appendFormat:@"\n%@>",padding];
        [childController addDescriptionToString:string indentLevel:indentLevel + 1];
    }
}

@end
Run Code Online (Sandbox Code Playgroud)


eri*_*ice 8

最快的方法(在lldb/Xcode调试器中):

po [UIViewController _printHierarchy]
Run Code Online (Sandbox Code Playgroud)