【发布时间】:2014-01-25 04:44:15
【问题描述】:
这已经困扰我一段时间了。我如何抵消使用po foo(或通过NSLog)在调试器中转储对象时发生的丑陋转义。我尝试了多种方法来实现-description 或-debugDescription 均无济于事。
鉴于这个简单的类
@interface Foo : NSObject
@property NSDictionary* dict;
@end
@implementation Foo
- (NSString *)description {
// super.description for the <{classname} pointer> output
return [NSString stringWithFormat:@"%@ %@", super.description, self.dict];
}
@end
和人为的用法
Foo* f0 = [[Foo alloc] init];
f0.dict = @{ @"value": @0, @"next": NSNull.null };
Foo* f1 = [[Foo alloc] init];
f1.dict = @{ @"value": @1, @"next": f0 };
Foo* f2 = [[Foo alloc] init];
f2.dict = @{ @"value": @2, @"next": f1 };
f0 得到了不错的输出
(lldb) po f0
<Foo: 0x8cbc410> {
next = "<null>";
value = 0;
}
f1 的可容忍输出
(lldb) po f1
<Foo: 0x8cbc480> {
next = "<Foo: 0x8cbc410> {\n next = \"<null>\";\n value = 0;\n}";
value = 1;
}
f2 的可怕输出
(lldb) po f2
<Foo: 0x8cbc4b0> {
next = "<Foo: 0x8cbc480> {\n next = \"<Foo: 0x8cbc410> {\\n next = \\\"<null>\\\";\\n value = 0;\\n}\";\n value = 1;\n}";
value = 2;
}
在调试现实世界的对象层次结构时,这很难快速解析。我假设自从转储类似嵌套的 NSDictionary 后,我还缺少其他一些技巧
NSDictionary* d0 = @{ @"value": @0, @"next": NSNull.null };
NSDictionary* d1 = @{ @"value": @1, @"next": d0 };
NSDictionary* d2 = @{ @"value": @2, @"next": d1 };
保持缩进,避免逃避地狱
(lldb) po d2
{
next = {
next = {
next = "<null>";
value = 0;
};
value = 1;
};
value = 2;
}
更新
切换到-debugDescription 并简单地转发到字典
@implementation Foo
- (NSString *)debugDescription {
return self.dict.debugDescription;
}
@end
失去递归输出
(lldb) po f2
{
next = "<Foo: 0x8b70e20>";
value = 2;
}
在内部,NSDictionary 必须依赖于 -description,我在此示例中没有实现它,只有 -debugDescription。切换到类似下面的东西
@implementation Foo
- (NSString *)description {
return self.dict.description;
}
- (NSString *)debugDescription {
return self.dict.debugDescription;
}
@end
也会产生同样糟糕的输出
(lldb) po f2
{
next = "{\n next = \"{\\n next = \\\"<null>\\\";\\n value = 0;\\n}\";\n value = 1;\n}";
value = 2;
}
【问题讨论】:
-
如果在
Foo description方法中将self.dict替换为[self.dict debugDescription]会发生什么? -
@rmaddy 遗憾的是它产生了相同的输出。这并不奇怪,因为
-[NSDictionary description]和-[NSDictionary debugDescription]产生相同的输出。NSArray的情况并非如此,它会为-debugDescription产生更差的 IMO 输出。但是,NSArray在这两种情况下仍然存在类似的转义问题。 -
当您在调试器中执行
po d2时,它应该调用debugDescription。由于这似乎给出了很好的输出,我希望明确地调用它会有所帮助。如果你实现Foo debugDescription并在你的对象上调用debugDescription会怎样? -
@rmaddy 是的,但默认情况下
-debugDescription只是委托给-description,除非明确覆盖。NSArray是我知道的这样一个地方,但NSDictionary没有。我将编辑我的问题以对此进行扩展。
标签: ios objective-c xcode debugging lldb