如何在调试器控制台中获取 NSDictionary 对象的值/键



>我设置了一个断点...

如果我这样做:

(lldb) print [self dictionary]
(NSDictionary *) $5 = 0x0945c760 1 key/value pair

但如果我这样做:

(lldb) print [[self dictionary] allKeys]
error: no known method '-allKeys'; cast the message send to the method's return type
error: 1 errors parsing expression

即使我尝试访问我知道的密钥在那里。

(lldb) print [[self dictionary] objectForKey:@"foobar"]
error: no known method '-objectForKey:'; cast the message send to the method's return     type
error: 1 errors parsing expression

我做错了什么?

error: no known method '-objectForKey:'; cast the message send to the method's return type

因此,它告诉您它不能仅从消息发送的名称推断返回类型信息 - 这完全没问题。它甚至告诉您必须如何确切地解决这个问题 - 您必须将消息发送到方法的返回类型

启动Apple的文档,我们发现- [NSDictionary objectForKey:]返回id - 通用的Objective-C对象类型。强制转换为 id(甚至更好,如果您知道字典包含哪些类型的对象,则强制转换为该确切的对象类型)可以解决问题:

(lldb) print (MyObject *)[(NSDictionary *)[self dictionary] objectForKey:@"foobar"]

lldb 命令打印需要您要打印的值是非对象。 您应该用于打印对象的命令是 po。

当你告诉 lldb 打印值时,它会查找一个名为 allKeys 的方法,该方法返回一个非对象并失败。 请改用以下命令...

po [[self dictionary] allKeys]

要在 GDB 或 LLDB 中打印对象的description,您需要使用 print-objectpo

(lldb) po [self dictionary]
(lldb) po [[self dictionary] objectForKey:@"foobar"]

为什么不干脆做

NSLog(@"dict: %@", dictionary);

NSLog(@"dict objectForKey:foobar = %@", [dictionary objectForKey:@"foobar"]);

目前 lldb 中似乎有一个错误,导致po dictionary[@"key"]打印空行而不是键的值。请改用[dictionary[@"key"] description]获取值。

最新更新