How free memory immediately in iOS?

点点圈 提交于 2019-12-24 10:01:48

问题


When you do a release, you do not immediately remove the memory. I used this code and I can see the memory before and after the use of release and it do not change. Ok, it will be release after some time.

But, what can I do for release all memory I can before start a library that will use a lot of memory? Or how can I immediately release memory?


回答1:


Memory Management is a big thing in iOS but this tidbit of information helped me a lot during my development.

"Each object has a "retain count" which is increased by calling "retain" and decreased by calling "release". Once the retain count hits 0, the object is released and the memory can be used for something else.

You can "autorelease" objects. This means the retain count isn't immediately decreased, but is decreased the next time the current autorelease pool is drained.

iOS apps have an event loop in which your code runs. After each iteration of the event loop, the autorelease pool is drained. Any object with a retain count of 0 is released.

By default, autoreleased objects are returned by methods that don't begin with new, copy, mutableCopy, retain or init. This means you can use them immediately but if you don't retain them the object will be gone on the next iteration of the run loop.

If you fail to release retained objects but no longer reference them then you will have a memory leak, this can be detected by the leaks tool in Instruments.

One strategy is to autorelease everything returned by the above named methods and store objects in retain properties (or copy for strings). In your object's dealloc method, set all your properties to nil. Setting a retain/copy property to nil releases the object that it currently points to. As long as you don't have any circular references (avoided by not using retain properties for "parent" objects such as delegates), you will never encounter any leaks."

here is the link to the thread for this information

http://www.quora.com/What-is-the-best-way-to-understand-memory-management-in-iOS-development

It's a good thread with some useful code examples as well as other references.




回答2:


Release frees the memory immediatly (assuming it's the last release). That means, it can be used by your application again when allocating. Note that every applications have some chunks (pages) of free memory assigned by system and when allocating/deallocating part of a page, the released memory is not returned automatically to the system. It's just marked as free and can be used again by the application.

To understand all this, you need to learn something about how operating systems handle memory allocation, virtual memory etc.



来源:https://stackoverflow.com/questions/8186056/how-free-memory-immediately-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!