recursiveDescription
在调试一个视图层级时非常有用。视图控制器层级也非常重要,是否有类似的方法可以使用?
recursiveDescription
在调试一个视图层级时非常有用。视图控制器层级也非常重要,是否有类似的方法可以使用?
要简明地回答,我在Xcode的调试器控制台中使用以下命令打印视图控制器层次结构:
po [[[UIWindow keyWindow] rootViewController] _printHierarchy]
P.S. 这只适用于ios8及以上版本,仅用于调试目的。
帮助我发现这个以及许多其他精彩调试技巧的文章链接是这个。
编辑1:在Swift 2中,您可以通过以下方式打印层次结构:
UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_printHierarchy")
编辑2:在Swift 3中,您可以通过以下方式打印层次结构:
UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
更新 - 现在苹果提供了类似的功能,作为 _printHierarchy
方法,因此您不再需要使用此分类。
现在有:
这将在 UIViewController
中添加一个 recursiveDescription
方法,打印出视图控制器层次结构。非常适合检查是否正确添加和删除子视图控制器。
代码非常简单,在上面的 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
最快的方法(在lldb/Xcode调试器中):
po [UIViewController _printHierarchy]
UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_printHierarchy")
- rob mayoffpo UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
- pbodsk