简体   繁体   中英

iphone memory management issue

How to check if an object has been released from the memory?

I know a object has to be released manually when we use alloc|copy|retain to create that object. if use the instance class method ( NSString stringwithformat: ), the object will be released automatically by NSAutoRealeasePool , however, sometime there have some object used to release at the (void)dealloc function there.

Can anybody tell me

  1. What is the difference between [object release] instantly after alloc function, [object release] at (void)dealloc ,and NSAutoReleasePool to release the object?

  2. When is the (void)dealloc function being called and when is the NSAutoReleasePool release the memory, I know it is every loop cycle, how can I check it from code?

  3. When I declared a variable in the header and set the property as retain, I still can use the alloc function to that object but not cause a memory leak, but from this post it seems like once declared a retain object at header, then you no longer can alloc the object because both will retain the object,can anybody tell me why I still can code like this without causing any memory leak?

  1. [object release] releases your object immediately. After sending a release message you should not use the object again - unless you absolutely know you still have a retain on that object. If yours was the last retain the memory could be freed during the call to release. Autorelease frees an object 'sometime later' the system does not guarantee anything about the meaning of 'later' other than that it will be after the scope of the current message.

  2. See above, there is no real qay to guarantee when dealloc is called following autorelease from the point of view of your code. You should just assume it is sometime after the return of the method where you send the autorelease message.

  3. You simply need to balance retain and release. If you have one to many (as is likely i nthe situation you describe) that is a leak. Conversely if you have unbalance the other way, you will generate a more destructive error when you access freed memory.

The correct sequence for a retained property is:

  1. alloc init // retain == 1

  2. set the property // retain == 2 due to setProperty calling retain.

  3. release the object // retain == 1

Which leaves a retain count of one, no memory leak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM