Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an NSValue back to the struct type that was stored in it?

I'm storing Chipmunk Physics' cpShape objects in an NSMutableDictionary by way of NSValue objects and the following lines of code:

NSValue *shapeValue = [[NSValue alloc] initWithBytes: shape objCType: @encode(cpShape)];
[staticBodiesInUse setObject: shapeValue forKey: name];

I now need to get the cpShape back out, to compare it to another shape. How can I do that? I see a getValue: method in NSValue but it needs a buffer, not too sure what to do with it.

like image 269
Luke Avatar asked Feb 04 '13 11:02

Luke


2 Answers

So the answer by trojanfoe is only partly correct.

There is a huge problem with doing that. When you create the NSValue that way, you are copying the cpShape struct, and getting it back out, you are copying it again. cpShape structs are pretty much exclusively used by reference. Each time you copy it, you get a new reference to the new copy, and some of those copies exist on the stack and get destroyed silently and automatically. Very very bad.

Instead you want to create a NSValue using [NSValue valueWithPointer:shape] and get that pointer back using [value pointerValue]. This way the NSValue is only storing a pointer to the original cpShape.

like image 137
slembcke Avatar answered Oct 23 '22 22:10

slembcke


Isn't it simply:

NSValue *value = [staticBodiesInUse objectForKey:name];
cpShape shape;
[value getValue:&shape];
like image 8
trojanfoe Avatar answered Oct 23 '22 22:10

trojanfoe