问题描述:

I am not familiar with C. I have a method created by someone else that has a CFDicionary that was created like this

touchBeginPoints = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);

point = (CGPoint *)malloc(sizeof(CGPoint));

CFDictionarySetValue(touchBeginPoints, touch, point);

I would like to dealloc the dictionary now. As far as I understand, I have to go item by item on whatever number of entries the dictionary has and free each one.

something like

 free((void *)CFDictionaryGetValue(touchBeginPoints, ...));

CFDictionaryRemoveValue(touchBeginPoints, ...);

So, how do I iterate thru this CFDictionary freeing each point stored there and removing each dictionary entry?

thanks for any help.

网友答案:

You don't.

You read this page: http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html#//apple_ref/doc/c_ref/CFDictionaryValueCallBacks

You recognise that by default, the standard dictionary will call CFRetain() to hold on to the value you pass it, and CFRelease() to let go of it. You think "...but CFRetain() is not appropriate to be called against CGPoint". You realise that all those people who told you to just release the dictionary will be leaking at best and crashing at worst.

You then create a structure like this:

CFDictionaryValueCallBacks myValueCallbacks = {
  0,
  NULL,
  myRelease,
  NULL,
  NULL
};

and pass that as the valueCallbacks argument when creating the dictionary (the last argument). The myRelease function should look like this:

void myRelease ( CFAllocatorRef allocator, const void *value )
{
    free(value);
}

Now, whenever the dictionary releases the values, it will call free() on them for you.

Having said all that, if you're a newcomer to C, this is not the place to start.

网友答案:

You can use Objective-C's toll-free bridging between CFDictionary and NSDictionary, if you'd like:

[(id)touchBeginPoints release]

网友答案:

No need to iterate through it, just release it with the CFRelease function. For further details and information refer to Apples Memory Management Programming Guide for Core Foundation on the iPhone Dev Center.

In your case:

CFRelease(touchBeginPoints);
相关阅读:
Top