我有以下实例方法(改编自应用程序编程指南中事件处理部分的清单3-6):
- (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位字节。我不知道如何在touchOriginPoint同时返回free()。
发布于 2010-01-27 07:27:01
如果您不关心轻微的性能损失,请使用NSMutableDictionary并将点存储为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内存的位置。因此,在创建字典时必须传递值回调。
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);
...发布于 2010-01-27 07:26:19
如果必须从函数返回malloc'd值,则将释放内存的责任传递给调用函数或其调用者之一。
因为我们看不到调用函数,所以不能再进行诊断。
发布于 2010-01-27 07:26:21
如果要返回分配的对象,那么要么需要调用方free()它,要么需要使用某种类型的垃圾收集(这样就可以自动释放它)。
https://stackoverflow.com/questions/2145152
复制相似问题