Here is the problem:
I am passing a pointer to an object to performSelector:withObject
via [NSValue valueWithPointer:]
for example like this:
// GVertex is NSObject subclass
GVertex *vertex = [[GVertex alloc] initWithX:5.0f andY:4.5f]];
GVertex **vertexPtr = &vertex;
// later in code when I need to process the vertex
[self performSelector:@selector(processVertex:) withObject:[NSValue valueWithPointer:vertexPtr]];
then in my processVertex:(NSValue *)vertexValue
method I want to get the passed vertex and I do it like this:
- (void)parseVertex:(NSValue *)vertexValue
{
GVertex *vertex = (GVertex *)[vertexValue pointerValue];
...
[vertex setFlags:32]; <<-- This gives me EXC_BAD_ACCESS
...
}
I have tried many combinations of (*) and (&) everywhere but can't get it to work. What am I doing wrong ? Thanks.
The pointer you're putting into the NSValue
is a pointer to a pointer (or the address of a pointer), but you're retrieving it as if it's a plain object pointer. Moreover, the pointer whose address you're taking is a local variable -- that address is going to be garbage in the context of a new method.
This should work if you just store the (single) pointer in the NSValue
:
[self performSelector:@selector(processVertex:) withObject:[NSValue valueWithPointer:vertex]];
Beware of memory management issues, however -- NSValue
does not copy or take ownership of the memory at that pointer.