当在调试器中查看实例变量的地址时,如何通过输入给定的内存地址获取类?
我知道相反的情况(从实例获取地址)可以使用调试器中的p someObjectInstance
或代码中的NSLog(@"%p", someObjectInstance);
。有没有类似的方法来做到这一点?
当在调试器中查看实例变量的地址时,如何通过输入给定的内存地址获取类?
我知道相反的情况(从实例获取地址)可以使用调试器中的p someObjectInstance
或代码中的NSLog(@"%p", someObjectInstance);
。有没有类似的方法来做到这一点?
gdb
或 lldb
中,则可以执行以下操作:po [(id)(0xDEADBEEF) class]
NSString *input = @"0xFAFAFA";
unsigned address = UINT_MAX; // or UINT_MAX
[[NSScanner scannerWithString:input] scanHexInt:&address];
if (address == UINT_MAX)
{
// couldn't parse input...
NSLog(@"failed to parse input");
return 0;
}
void *asRawPointer = (void *) (intptr_t) address;
id value = (__bridge id) asRawPointer;
// now do something with 'value'
NSLog(@"%@", [value class]);
在调试器中,您可以对您怀疑是有效的Objective-C对象的地址使用po
。例如,在我的程序运行中,我知道0x9549ee0
指向一个UIFont对象。
使用po
,我看到以下内容:
(gdb) po 0x9549ee0
<UICFFont: 0x9549ee0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 14px
这将打印出您使用以下方式获得的相同信息:
NSLog(@"%@", someObject);
即是指[someObject description]
的结果。通常这个结果包含比仅仅类名更有用的信息(正如上面的例子所示)。
正如Richard J. Ross III所提到的,你需要小心使用这种方法。调试器通常可以判断地址是否无效,例如:
(gdb) po 0x9449ee0
0x9449ee0 does not appear to point to a valid object.
但是它的实现并不是绝对可靠的。如果你在程序中使用代码来实现,很可能会导致程序崩溃。
当然,你也可以直接在变量上使用po
命令:
(gdb) po font
<UICFFont: 0x9549ee0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 14px
unsafeBitCast
。(lldb) e let $vc = unsafeBitCast(0x7fd0b3e22bc0, GooglyPuff.PhotoCollectionViewController.self)
(lldb) po $vc.navigationItem.prompt = "WOOT!"