IOS memory management: Relationship between reference count, arc, automatic release pool autoreleasepool, and convenient methods

Source: Internet
Author: User

Part of the content is taken from objective-C basic tutorial and the Internet

Reference count

Cocoa uses the reference counting mechanism. Each object has an associated "integer retaincount" to record the usage of the object. Retaincount + 1 when the object is referenced, retainCount-1 after the use of the external environment end object. When retaincount is 0, the object is destroyed.

When we use alloc, new, or copy, we need to destroy this object. The release function only deletes the retaincount value of an object by 1, rather than deleting the object. When retaincount = 0, the system sends a dealloc message to the object,In addition, do not manually call dealloc, because we do not know when, where, and who will use this object. The reference counting mechanism should be honestly used to manage the memory.

In addition to release and autorelease, the function that releases object ownership is a delay operation. The following describes in detail.

When we see the following code,

The first problem: the memory management of dateformatter should be well understood, because [nsdateformatter alloc], we need to release it.

-(Nsstring *) date2string :( nsstring *) Str


Nsstring * datestring;

Nsdate * currenttime = [nsdate date];

Nsdateformatter * dateformatter = [[nsdateformatter

[Dateformatter setdateformat: Str];

Datestring = [dateformatter stringfromdate: currenttime];


Return datestring;


In this functionNsstring* DatestringAndNsdate *
These two variables are used for memory management. Also, what about memory management when the local datestring is used as the return value? This is a good question.

We found that the value assignment method of datestring is [dateformatter stringfromdate: Current]. Obviously, it does not use alloc, new, or copy. In objective-C basic tutorial, assume that the reference count value of the datestring object is 1 when it is returned. The word "hypothesis. This book is really a basic tutorial!

As mentioned in objective-C basic tutorial, there are no stack objects and no temporary objects in OC. So what is this datestring?

Now, we can put them into the scope of automatic release, so we can understand that the new alloc object in [dateformatter stringfromdate: Current. This object is autorelease.

The automatic release is described in detail below.

Automatic release pool autoreleasepool

The Auto Release pool is an instance of the NSAID utoreleasepool, which contains the object that receives the autorelease message. When an automatic release pool is destroyed (dealloc), it sends a release message to each object in the pool (if you send an autorelease message to an object multiple times, when the Auto Release pool is destroyed, this object will also receive the same number of release messages ). It can be seen that an automatically released object can survive at leastAutomatic release pool destruction.

To put it simply, return the pointer of the variable on the partial stack (in the C ++ tone). How can this object be released? Objective-C invented the automatic release mechanism.

-(OBJ *) foo


OBJ * temp = [[OBJ alloc] init];

Return [OBJ autorelease]; // only the keyword autorelease is added to the returned result.


In the basic objective-C tutorial, autorelease is a delayed release mechanism to ensure that the variables on the partial stack can be normally used by the outside.

But when did the system be released? At the beginning of each event cycle, the system automatically creates an automatic release pool;

At the end of each event cycle, the automatic release pool is automatically destroyed. Generally, you can understand that when your code continues to run, the automatically released pool will not be destroyed, during this period, you can also safely use the automatically released objects. When your code stops running and starts waiting for user input (or other events, the automatically released pool will be released, and objects in the pool will receive a release message, and some may be destroyed.

It is difficult to determine the time. If the destruction time of the automatic release pool is too early, the program will be very dangerous. I am afraid this will be difficult to meet the requirements of programmers.

The disadvantage of the automatic release pool is that it delays the release of objects and occupies a large amount of memory resources when a large number of automatically released objects exist. Therefore, you need to avoid releasing a large number of objects automatically. In addition, in the following two cases, you need to manually create and manually destroy the automatic release pool:

1. When other threads are enabled outside the main thread: the system will automatically generate and destroy the automatic release pool in the main thread.

2. When you create a large number of automatically released objects in a short period of time: timely destruction helps to effectively use the limited memory resources on the iPad.

Therefore, I do not recommend using the autorelease mechanism. If you encounter the above example, use a typical solution. an external object is responsible for deleting the OBJ object to prevent memory leakage.

Memory Management of convenience method

Related to automatic release, there is a constructor method. The objects constructed by them are directly released objects. This kind of constructor method is called a convenient method. For example, the string in the following sentence is an automatically released object, and stringwithformat is a convenient method.

Nsstring * string = [nsstring stringwithformat: @ "autoreleasestring"];

Let's take a few examples of convenient methods to facilitate your future development.

1.NsarrayOfArraywithobjects: AndArraywitharray:.



In other words, we can use the objects returned by these methods, but we still cannot determine when dealloc will be returned. Can we take the initiative to delete the objects returned by these "convenient functions? If the program contains a large number of "convenient functions", this will undoubtedly occupy a large amount of memory space.

Can this "convenient function" be avoided in a loop "?

Now we have explained that the autorelease method will release an object after a period of time, during which we can safely use this object. So how long is this time?

The automatic release mechanism has been introduced above. objects generated by convenient functions can survive at leastAutomatic release pool destruction.

ARC (auto reference counting)

The above text introduces "reference count". Here we have a more advanced automatic reference count.

Please refer to this article

/*************************************** * The following describes the typical applications ****************************?

The role of self. xxx.

Nsinteger I = 0;

The first line _ extramessage = [ftexportmessage
Alloc] init];

Row 2 // self. extramessage =
[[Ftexportmessage alloc] init];

I = [self. extramessage

[Self. extramessage

You will find that retaincount is 1 in the first line. However, do not use the second line of code. The retaincount value is 2. If you call release in time, the object will not be deleted.

Beginners are prone to mistakes. Self. XXX is used everywhere.

Nsarray and nsdictionary add elements, memory management

This type of Collection class only adds the retaincount of the "element" to 1. Similarly, when nsdictionary release, the "element"

-(Void) preparedata


_ Buddymsg = [exportmsgentity

_ Pgmsg = [[exportmsgentity alloc] init];

_ Dgmsg = [[exportmsgentity alloc] init];

_ Msggroup = [[nsmutabledictionary
Alloc] initwithobjectsandkeys:

Self. buddymsg, kmsgbuddy,

Self. pgmsg, kmsgpggroup,

Self. dgmsg, kmsgdggroup, nil];

Int I = 0;

I = self. buddymsg. retaincount; // At this time I = 2


The above code changes the retaincount of self. buddymsg from 1 to 2. Then, after nsdictionary analysis, please refer to the following situation.

-(Void) deletedictionary


[Self. msggroup

Int I = 0;

I = self. buddymsg. retaincount; // At this time I = 1


The above Code makes the retaincount of self. buddymsg reduce from 2 to 1

Summary: when using these "sets", do not think that the elements in the "set" release will be automatically deleted. Finally, the element is its own release resource.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.