Obj-C:定期转储应用程序视图的层次结构

时间:2015-10-29 02:50:32

标签: ios objective-c xcode debugging

我们知道可以使用此调试器命令在断点中转储视图层次结构:

po [[UIWindow keyWindow] recursiveDescription]

定期执行相同操作的最佳方法是什么,以便每次更改层次结构时,新层次结构都将转储到日志中?

1 个答案:

答案 0 :(得分:0)

这是一个有用的实现:

//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// This function will dump the app's view hierarchy periodically.
// No change - no printing
// 'gap_between_calls' comes in units of seconds.
// Tips: use times_to_run:1 to run once. use times_to_run:INT_MAX for non-stop
//
void dumpViewsHierarchyPeriodically(int times_to_run, float gap_between_calls)
{
    static NSMutableString *lastText = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        for (int i=0; i<times_to_run; i++) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                NSArray *windows = [[UIApplication sharedApplication] windows];
                int count = (int)windows.count;
                NSMutableString *txt = [NSMutableString new];
                for (int i=0; i<count; i++) {
                    UIWindow *wnd = windows[i];
                    #pragma clang diagnostic push
                    #pragma clang diagnostic ignored "-Wundeclared-selector"
                    [txt appendString:[NSString stringWithFormat:@"\nwindow[%i/%i]: %@",
                                       i+1, count, [wnd performSelector:@selector(recursiveDescription)]]];
                    #pragma clang diagnostic pop
                }
                //log only if defferent than previous
                if (!lastText || ![txt isEqualToString:lastText]) {
                    NSLog(@"%@", txt);
                    lastText = txt;
                }
            });
            if (i+1 < times_to_run) {
                [NSThread sleepForTimeInterval:gap_between_calls];
            }
        }
    });
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

对于单次运行,可以使用以下内容:

//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// This function will dump the app's view hierarchy
void dumpViewsHierarchy()
{
    NSArray *windows = [[UIApplication sharedApplication] windows];
    int count = (int)windows.count;
    for (int i=0; i<count; i++) {
        UIWindow *wnd = windows[i];
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Wundeclared-selector"
        NSLog(@"\nwindow[%i/%i]: %@", i+1, count, [wnd performSelector:@selector(recursiveDescription)]);
        #pragma clang diagnostic push
    }
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^