2

我有以下代码:

eachShape(void *ptr, void* unused) {
  cpShape *shape = (cpShape *) ptr;
  id obj = shape->data;
  NSLog(@"shape->data: %@", obj);  // this is where EXC_BAD_ACCESS can occur
  ...

你们中的一些人可能会从 iPhone 开发中使用的 Chipmunk 物理框架中认出它。基本上我在这里崩溃是因为我在其他关于 cpSpace 的代码中所做的事情,但我想弄清楚这里发送了什么对象类型并导致我的 NSLog 语句崩溃(并造成其他破坏)。

将类型和/或内容从 void 指针转储到 NSLog 调用的最佳方法是什么?

4

2 回答 2

2

I think your problem is that %@ is only meaningful if shape->data really points to an Objective-C object, since using it triggers the sending of -description to obj. But if for example shape->data points to an int, the message will be send to an object that does not really exists. Instead, some memory location may be interpreted as the raw bytes of an object, causing the runtime to crash.

To answer your question: The type of an void pointer is void *, and the type of the pointer's target is void. You can print the pointer's value with %p, but I doubt that this is what you want.

So if you are sure that the memory location where shape->data points to represents an Objective-C object, and you have access to the class code, you can override -description to print whatever information you like.

于 2010-01-12T17:53:55.260 回答
1

The %@ format specifier is interpreted as

Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.

Basically, if ptr doesn't point to an Objective-C object, you're out of luck!

Either way, you should cast the void * pointer to something meaningful..

于 2010-01-12T17:55:17.413 回答