这已经困扰我一段时间了。如何抵消在调试器中转储对象时发生的丑陋转义po foo
(或通过NSLog
)。我尝试了多种方法来实施-description
or -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;
}
UPDATE
切换到-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;
}