问题描述
我有以下实例方法(改编自《 iPhone应用程序编程指南》中事件处理"部分的清单3-6 ):
I have the following instance method (adapted from Listing 3-6 of the Event Handling section in the iPhone Application Programming Guide):
- (CGPoint)originOfTouch:(UITouch *)touch
{
CGPoint *touchOriginPoint = (CGPoint *)CFDictionaryGetValue(touchOriginPoints, touch);
if (touchOriginPoint == NULL)
{
touchOriginPoint = (CGPoint *)malloc(sizeof(CGPoint)); // leaks
CFDictionarySetValue(touchOriginPoints, touch, touchOriginPoint);
*touchOriginPoint = [touch locationInView:touch.view];
}
return *touchOriginPoint;
}
由于对 malloc()
的调用,我的应用程序有时每隔16个字节就会泄漏一次.我不确定如何在 free()
也返回它的同时返回 touchOriginPoint
.
Every once in a while my app leaks 16 Bytes as a result of the call to malloc()
. I'm not sure how to return touchOriginPoint
while free()
ing it as well.
推荐答案
如果您不关心次要的性能损失,请使用 NSMutableDictionary
并将该点存储为 NSValue
:
If you do not care a minor performance loss, use an NSMutableDictionary
and store the point as an NSValue
:
NSValue* touchOriginPointValue = [touchOriginPoints objectForKey:touch];
if (touchOriginPointValue == nil) {
touchOriginPointValue = [NSValue valueWithCGPoint:[touch locationInView:touch.view]];
[touchOriginPoints setObject:touchOriginPointValue forKey:touch];
}
return [touchOriginPointValue CGPointValue];
如果必须使用 CFDictionary
方法,则必须找到一个地方,以在没有值的情况下 free
那些 malloc
-ed的内存需要.因此,创建字典时必须传递值回调
If you must use the CFDictionary
approach, you have to find a place to free
those malloc
-ed memory when the values are not needed. Therefore, you have to pass the values callbacks when creating the dictionary
static void free_malloced_memory (CFAllocatorRef allocator, const void *value) {
free((void*)value);
}
static const CFDictionaryValueCallBacks values_callbacks = {0, NULL, free_malloced_memory, NULL, NULL};
...
touchOriginPoints = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, & values_callbacks);
...
这篇关于当函数返回malloc()的结果时,如何在malloc()之后释放()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!