views:

249

answers:

2

Since there is no counterpart to NSValue in Core Foundation, how are we supposed to store C structs in a CFMutableDictionary?

+1  A: 

CFMutableDictionary

CFDictionaryAddValue A CFType object or a pointer value to add to the dictionary.

you just pass a pointer to your struct.

CiNN
Wow I definitely should have looked a bit closer at the documents. Do I have to supply a custom callback or can I just use it as is?
James
This will crash when the pointer to the struct is handed to the default retain method, which expects a CFType. You have to overload the callbacks in order for this to work.
Rob Napier
+3  A: 

First, you can put an NSvalue in a CFMutableDictionary as-is, so the answer is "use NSValue." But I assume the rest of your question is "without using any Cocoa objects." In that case, just create a non-retaining CFMutableDictionary, and you can put any pointer you want into it. See "Defining Custom Collection Callbacks" for some example code. I use these a lot.

Remember that these still have to be pointers, so you're going to have to allocate your structs on the heap, not the stack. And that means that memory management is now your problem. Of course you could create a custom set of callbacks that do whatever you want, so if you're using boost or something else with its own ref-counting system, you can still implement that with CFMutableDictionary.

And of course you can replace the struct with a small data object. That's usually a lot easier. But different problems need different solutions.

Rob Napier
Thanks Rob! Exactly what I was looking for: Non-retaining dictionary.
James