【发布时间】:2013-01-07 10:07:05
【问题描述】:
recursiveDescription 在调试视图层次结构时非常有用。 View controller 层次结构也很重要,有没有等价的?
【问题讨论】:
标签: objective-c ios uiviewcontroller
recursiveDescription 在调试视图层次结构时非常有用。 View controller 层次结构也很重要,有没有等价的?
【问题讨论】:
标签: objective-c ios uiviewcontroller
为了简明扼要,我在 Xcode 的调试器控制台中使用以下命令来打印视图控制器层次结构:
po [[[UIWindow keyWindow] rootViewController] _printHierarchy]
附:这仅适用于 ios8 及更高版本,仅用于调试目的。
链接到帮助我发现这个和许多其他出色调试技术的文章的链接是this
编辑 1: 在 Swift 2 中,您可以通过以下方式打印层次结构:
UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_printHierarchy")
编辑 2: 在 Swift 3 中,您可以通过以下方式打印层次结构:
UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
【讨论】:
UIApplication.sharedApplication().keyWindow?.rootViewController?.valueForKey("_printHierarchy")
po UIApplication.shared.keyWindow?.rootViewController?.value(forKey: "_printHierarchy")
更新 - 类似的功能现在以 Apple 提供的形式作为 _printHierarchy 方法提供,因此您不再需要此类别。
现在有:
Github: Recursive description category for view controllers.
这向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]
【讨论】: