Objective-C diary 7 Memory Management

Source: Internet
Author: User

Cocoa memory management method:Retain, releaseAndAutorelease

Summary:

Each object maintains a reserved counter. when an object is created, its reserved counter value is 1. When the object is retained, the counter is + 1. When the object is released, the counter is retained-1; when the reserved counter value is 0, the object is destroyed. When the object is destroyed, the dealloc method of the object is called first, and the Occupied memory is recycled for other objects.

When an object receives an autorelease message, its reserved counter value does not change immediately. On the contrary, this object is only put into the NSAID utoreleasepool. When the automatic release pool is destroyed, a release message is sent to all objects in the pool. All automatically released objects keep the counter value-1. If the reserved counter value is 0, the object is destroyed.

When using appkit, objective-C will create and destroy the Auto Release pool for you at the appropriate time.

 

Prime rule for Memory Management
1. UseNew, alloc, copyMethod to create an object, the counter value of this object is 1. When you no longer use this object, you need to send a release or autorelease message to this object
2. WhenOther methodsWhen an object is obtained, assuming that the counter of this object is 1 and has been set to Auto Release, no operation is required to ensure that the object is cleared.
3. If an object is retained and eventually needs to be released or automatically released, the retain method and the release method must be used equally.

To put it simply: if you use the new, alloc, or copy methods to obtain an object, you must release or automatically release the object.

I. Temporary objects

You do not intend to possess this object for a long time: if you use the new, alloc, and copy methods to obtain an object, you need to arrange the object to die. Generally, release messages are used for implementation.
Eg:
Nsmutablearray * array;
Array = [[nsmutablearray alloc] init]; // COUNT = 1
[Array release]; // COUNT = 0

Note:

If you use other methods to obtain an object such as arraywithcapacity: method, you do not need to worry about it if you destroy the object:
Nsmutablearray * array;
Array = [nsmutablearray arraywithcapacity: 10]; // COUNT = 1 autoreleased
Cause:
The arraywithcapacity method does not belong to one of the alloc, new, and copy methods. Therefore, we can assume that the calculator value is 1 when the object is returned and has been set to Auto Release.
When the automatic release pool is destroyed, the system sends a release message to the array object. This object retains the value of the calculator to 0, and the Occupied memory is recycled.

Also, the nscolor class
Nscolor * color;
Color = [nscolor bluecolor];
The bluecolor method does not belong to the alloc, new, or copy methods. Same as above

Ii. Owning objects

You want to always own this object. Common method: use these objects in instance variables of other objects to add them to or use them as global variables, for example, nsarray or nsdictionary.

If you are using new, alloc, or copy to create an object, the counter value of the object will be retained for 1, but you must release the object in the dealloc method of the object that owns the object.
-(Void) dostuff
{
Flonkarray = [nsmutablearray new]; // count 1
}
-(Void) dealloc
{
[Flonkarray release]; // count 0
[Super dealloc];
}

As mentioned above, you create an object through new, alloc, and copy. If you do not use these three methods to obtain the object from other methods, and you need to own the object, consider writing a GUI application. Program Event Loop
Eg: use the automatic release object. Code It can be changed:

 
-(Void) Dosuff {flontarray= [Nsmutablearray arraywithcapacity:10];//Count 1 autorelease (why is the cause of automatic destruction above)[Flontarray retain];//Count 2Autorelease if retain is not used, flontarray may be destroyed. The reason is that arraywithcapacity}-(Void) Dealloc {[flontarray release];//Count 1[Super dealloc];}

When the event loop ends or the automatic release pool is destroyed, flontarray will receive a release message to reduce the counter value from 2 to 1, and the counter value is greater than 0, so the object continues to exist. Therefore, you need to release the object in dealloc.

 

Let's look at this example.

 
IntI;For(I =0; I <1000000; I ++){ID Object=[Somearray objectatindex: I]; nsstring* DESC = [ObjectDescription];//Description: you do not need to ignore it here.}

In this case, 1 million description string objects may be generated, and the memory usage will continue to grow. These 1 million objects exist until the automatic release pool is destroyed.

Solution:

The solution is to create an automatic release pool in the loop so that the current automatic release pool is destroyed and a new automatic release pool is created every 1000 times:

NSAID utoreleasepool *Pool; Pool = [[NSAID utoreleasepool alloc] init];  Int  I;  For (I = 0 ; I < 1000000 ; I ++ ){  ID   Object = [Somearray objectatindex: I]; nsstring * DESC = [ Object  Description];  If (I % 1000 = 0  ) {[Pool release]; Pool = [[NSAID utoreleasepool alloc] init] ;}} [pool release] 

A New Auto Release pool is destroyed every 1000 times, and a new auto release pool is created. In addition, the description strings in the automatically released Pool cannot exceed 1000. In this way, the memory usage does not increase continuously; in the end, the operation cost of automatic release pool allocation and destruction becomes very small;

Note:

The automatic release pool is in the form of a stack: When you create a new automatic release pool, it will be added to the top of the stack (the stack works first-in-first-out ); objects receiving autorelease messages will be placed in the top Auto Release pool.If you add an object to the Auto Release pool and create a new auto release pool and destroy the newly created Auto Release pool, the automatically released pool object will still exist, because the automatic release pool containing this object still exists.

Iii. Garbage Collection

The objective-C garbage collector is an inherited garbage collector, which is triggered at the end of an event loop, just like the automatic release pool. Note that: if you develop an iPhone, you cannot use the Garbage Collector. In fact, when writing an iPhone program, Apple recommends that you do not use the autorelease method in your own code, but also avoid using convenience functions that automatically release objects.

 

In xcode, enable the garbage collection function (on the build tab of the project information window, select the required [-fobjc-GC-only] Option). No Mac or specific operations are required, buy a real machine that day and try again ......

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.