I have some code like:
- (SendFileInfo *)sendFileInfoForName:(NSString *)name {
for (SendFileInfo *sendFileInfo in sendArray)
{
if ([sendFileInfo.name isEqualToString:name])
{
return sendFileInfo;
}
}
return nil;
}
So the return value of this method will be autorelease.I use instruments to track the retain/release event of SendFileInfo;Sometimes SendFileInfo will release after autorelease,just like:
Retain/Autorelease/Release (3) 00:48.146.622 ipjsua -[SendFileQueue sendFileInfoForName:]
Retain +1 5 00:48.146.622 ipjsua -[SendFileQueue sendFileInfoForName:]
Autorelease 00:48.146.627 ipjsua -[SendMessageViewController refreshSendFileView:]
Release -1 4 00:48.155.558 GraphicsServices GSEventRunModal
But sometimes there is no release action, so the memory of this object will not be released.
Retain/Autorelease (2) +1 00:46.996.752 ipjsua -[SendFileQueue sendFileInfoForName:]
Retain +1 2 00:46.996.752 ipjsua -[SendFileQueue sendFileInfoForName:]
Autorelease 00:46.996.756 ipjsua -[SendMessageViewController refreshSendFileView:]
In the end, the reference count of the SendFileInfo object is equal to the time the sendFileInfoForName method is called(which does not release after autorelease). Memory leak! When does the release event happen? Why doesn't the release event happen in the same method?
An object will be released when there are no more references to it. The object you return, however is still strongly retained by the array
sendArray
. As soon as it leaves that collection, it will be released.All types of collections, NSArrays, NSSets and NSDictionaries will strongly reference the object you add, meaning that they will "live" for the duration of the array's lifetime.