从Objective-C的hex实例中获取类

当在debugging器中看到实例variables的地址时,如何通过input给定的内存地址来获取类?

我知道在debugging器或NSLog(@"%p", someObjectInstance);使用p someObjectInstance可以得到相反的结果(从实例获取地址NSLog(@"%p", someObjectInstance); 从代码中。 有没有类似的方式来做到这一点呢?

你所要求的是非常不安全的。 访问一个未知的内存位置通常是一个坏主意,但是因为你问:

编辑:如果在gdblldb里面,你可以这样做:

 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]); 

在debugging器中,您可以在您怀疑是有效的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]的结果。 这通常包含更多有用的信息,仅仅是类名(从上面的例子可以看出)。

理查德·J·罗斯三,提到你应该小心这样做。 debugging器通常可以判断地址是否无效,例如:

 (gdb) po 0x9449ee0 0x9449ee0 does not appear to point to a valid object. 

但是这样做的方式并不是万无一失的。 如果你要在程序中使用代码,可能会崩溃。

哦,当然你也可以直接在variables上使用po

 (gdb) po font <UICFFont: 0x9549ee0> font-family: "Helvetica"; font-weight: normal; font-style: normal; font-size: 14px 

希望这可以帮助。

右键单击debugging区域,然后selectdebugging区域帮助 – >查看内存位置

或者在Xcode文档中去

Xcode开发人员库 – > Xcode-> IDEs->debugging区帮助 – > 查看内存位置

在Swift中,你可以使用unsafeBitCast

 (lldb) e let $vc = unsafeBitCast(0x7fd0b3e22bc0, GooglyPuff.PhotoCollectionViewController.self) (lldb) po $vc.navigationItem.prompt = "WOOT!" 

阅读Swift的Grand Central Dispatch教程:第2/2部分