开发者

How to fix this potential memory leak?

I am new to objective c and I don't understand how there is a memory leak here:

MessageCustomCell *cell = [[MessageCustomCell alloc] initAutoreleaseWithLine:currentLine AndId:message.UID];
[[cell dateTime] setText:[formatter stringFromDate:message.Date]];
[[cell from] setText:message.From];
[[cell play] setTitle:@">" forState:UIControlStateNormal];    
[formatter release];   
return cell;

On the return cell; line the analyzer says that there is a "potential leak of an object allocated on line 207 and stored into cell." This is the line where cell is allocated but I'm returning cell so how is this a leak?开发者_运维百科 Thanks in advance for the help!


The issue, based on the name, is you are trying to return an auto released object in an init function. The static analyzer makes assumptions that instance methods beginning with init return ownership to the caller (increased retain count) even if you call it initAutorelease. The same goes for methods that begin with new. You will continue to get analyzer warnings until you change the name but what you are trying to do needs to be a convenience method of the class.

//Signature
+(id)cellWithLine:(int)line andId:(NSString*)mid;

//Sample Call
[MessageCustomCell cellWithLine:currentLine andId:message.UID];


return [cell autorelease];

Also, you are releasing formatter.


Before Fixing potential leaks we need to know what is retain and release. Retain is allocating memory, Release is deallocating memory.

NSstring *str = [[NSstring alloc] init]; Here we are allocating memory to 'str' variable. In the same .m file we need release the memory for the variable after completing the functionality of it. Simple write in the code [str release]; It won't cause any memory leaks.


Unless your method name begins with "new" (as in newMessageCell), "alloc" or contains "copy", the returned object is expected to be an autoreleased object. Your code returns the object with a reference count of 1 and a well-behaved caller will not decrement it beyond that. If the caller wishes to retain the cell to take ownership of it, it will do so.

To fix this leak, simply autorelease the cell.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜