3

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?

3
  • Posterity ... and reputation! ;) Commented May 17, 2010 at 17:18
  • Heh yeah I guess. I don't have a lot of free time to answer others' questions, but when I come across an interesting answer on my own, I like to give back. Commented May 17, 2010 at 20:12
  • Hey Tim, I'd like to keep the "C" tag. I know the question is about objective-c, but it's also about, specifically, a replacement for a "C" answer. Commented May 19, 2010 at 17:22

2 Answers 2

8
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:)

Sign up to request clarification or add additional context in comments.

Comments

1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.