views:

131

answers:

2

I figured out the answer to this question, but I couldn't find the solution on here, so posting it for posterity.

So, in Objective-C, how do you create an object out of a pointer in order to store it in objective-c collections (NSArray, NSDictionary, NSSet, etc) without reverting to regular C?

+8  A: 
NSValue *pointerObject = [NSValue valueWithPointer:aPointer];

This will wrap the pointer in an NSValue. To get it back out later use NSValue's instance method (pointerValue:)

DougW
+1  A: 

An alternative solution is to define a class that has methods that access/manipulate the contents of the pointer, then add instances of that to the array.

Don't bother subclassing NSValue as it really adds nothing to the solution.

Something like:

@interface FooPtr:NSObject
{
    void *foo;
}

+ fooPtrWithFoo: (void *) aFoo;

.... methods here ...
@end

I specifically chose an opaque (void *) as that tells the client "don't touch my innnards directly". In the implementation, do something like #define FOOPTR(foo) ((Foo *) foo) Then you can FOOPTR(foo)->bar; as needed in your various methods.

Doing it this way also makes it trivial to add Objective-C specific logic on top of the underlying datatype. Sorting is just a matter of implementing the right method. Hashing/Dictionary entries can now be hashed on foo's contents, etc...

bbum