我有以下的實例方法(改編自上市的iPhone應用程序編程指南中的事件處理部分的3-6):當函數返回malloc()的結果時,如何在malloc()後釋放()?
- (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;
}
在
每一次,而我的應用程序泄漏16個字節結果致電malloc()
。我不知道如何返回touchOriginPoint
而free()
也是如此。
感謝KennyTM,我會給這些回調函數一個鏡頭。 – 2010-01-27 16:24:30
CFDictionary是必需的,因爲UITouch不執行NSCopying。雖然實現回調函數有助於它不會消除所有相關的內存泄漏。 – 2010-02-02 15:18:22
@Shaun:對啊。但是由於複製是唯一的問題,您仍然可以使用'CFDictionary'作爲鍵,'NSValue'作爲值,並使用'&kCFTypeDictionaryValueCallBacks'值回調,以便CF可以自動跟蹤ref-counting。 – kennytm 2010-02-02 15:43:28