Add C pointer to NSMutableArray

nsmutablearray, objective-c, pointers

Solution

There's a class designed precisely for this: `NSPointerArray`. See Apple's docs here. For arbitrary pointers, you'll probably want to use the `NSPointerFunctionsOpaqueMemory` and `NSPointerFunctionsOpaquePersonality` options.

If `NSPointerArray` is not available (for example, if you're developing for iOS), then you could wrap your pointers using `-[NSValue valueWithPointer:]`, as long as the overhead of wrapping & unwrapping doesn't prove too slow.

Problem

I am writing an Objective-C program that deals with low level image memory. I am using ANSI-C structs for my data storage -- Full blown objects seem overkill seeing as the data I am storing is 100% data, with no methods to operate on that data. Specifically, I am writing a customizable posterization algorithm which relies on an array of colors -- This is where things get tricky. I am storing my colors as structs of three floats, and an integer flag (related to the posterization algorithm specifically). Everyhting is going well, except for one thing... [actual question] I can't figure out how to add pointers to an NSMutableArray! I know how to add an object, but adding a pointer to a struct seems to be more difficult -- I do not want NSMutableArray dereferencing my pointer and treating the struct as some sort of strange object. I want NSMutableArray to add the pointer its self to its collection. How do I go about doing this? Thanks in advance, G

Original source