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

pat*_*ick 13 objective-c ios lldb

我设定了一个断点......

如果我做:

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

但如果我这样做:

(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
Run Code Online (Sandbox Code Playgroud)

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

(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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

小智 17

你会说英语吗? - 看来你做得很好!啊,多么巧合,调试器也做到了!

非常好,我们完成了艰难的部分.现在您已经使用调试器了解彼此,让我们看看它的建议:

error: no known method '-objectForKey:'; cast the message send to the method's return type
Run Code Online (Sandbox Code Playgroud)

因此,它告诉你它不能仅仅从消息发送的名称中推断出返回类型信息 - 这完全没问题(一个不使用匈牙利表示法,对吧?).它甚至会告诉你你究竟如何解决这个问题-你必须将消息发送到该方法的返回类型.

解雇Apple的文档,我们发现- [NSDictionary objectForKey:]返回id- 通用的Objective-C对象类型.转换为id(或者甚至更好,如果你知道你的字典包含什么类型的对象,转换为确切的对象类型)就可以了:

(lldb) print (MyObject *)[(NSDictionary *)[self dictionary] objectForKey:@"foobar"]
Run Code Online (Sandbox Code Playgroud)


mmc*_*omb 14

lldb命令打印期望您要打印的值是非对象.您应该用来打印对象的命令是po.

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

po [[self dictionary] allKeys]
Run Code Online (Sandbox Code Playgroud)