Objective-C memory management-reference count, objective-c Memory Management

Source: Internet
Author: User

Objective-C memory management-reference count, objective-c Memory Management

When learning Objective-c, it is easy for beginners to get confused about the memory management part. A major reason is that the reference counting principle is not clear, I cannot understand the reference quantity of objects, so that the object's memory cannot be completely released. The apple official documentation on memory management is very simple and has only three principles:

If you follow these rules when writing code, you can avoid Memory leakage. However, if you write code by simply relying on the "Memory" of these rules, I am afraid I will not have a bottom in my mind, once you encounter a problem analysis problem, it is difficult to fundamentally find the cause of the problem. This article shares the analysis process of understanding the reference count, combined with the relevant graphics, we hope that you will have a deep understanding of the principle of object reference counting.

Encountered a problem? Analyze and test

What is the reference count of the current object?

Why do you want to raise this question? Many people will confuse the relationship between the number of pointers of objects and the number of references. If they do not understand this question, they will not understand the reference count of objects, of course, the memory cannot be correctly released. Before talking about this, let's take a look at the concepts of heap memory and stack memory,

The variable name is actually a symbolic address. During program compilation and connection, the system allocates a memory address to each variable name. In a program, you can find the corresponding memory address by using the variable name to read data from its storage unit. A pointer is a special variable because it stores the address of a variable. As shown in:

 

The above memory model I believe everyone knows that there is an indirect (Pointing) Relationship between the pointer and the object. Therefore, when the pointer points to an object, many people will think that this pointer references this object, and then they think that when the pointer points to an object, the reference count of this object will be increased by 1, this kind of understanding is a kind of perceptual understanding. In fact, for an object, it does not know how many pointers are directed to it. Its release only relies on reference counting. So what is reference counting? In objective-c, most objects are inherited from NSObject. NSObject contains a retainCount field used to save the referenced quantity. In other words, this field is the reference count. The NSObject class is defined as follows:
- (id)retain;
- (oneway void)release;
- (id)autorelease;
- (NSUInteger)retainCount;
- (NSString *)description;

Therefore, to facilitate understanding, we can simplify NSObject into the following model:

 

Whether an object can be released is used to determine whether its reference count is zero, that is, whether the retainCount field of the object is equal to 0, and the number of pointers to the object is irrelevant to the value of the retainCount field of the object, therefore, the number of pointers is not equal to the number of references. When the Pointer Points to this object, it only assigns a value to the pointer variable and does not modify the retainCount value of the object. Therefore, when the pointer points to an object, the reference count of this object remains unchanged.

The code above is used as an example. When we call the new method of the Test object, the retainCount value is automatically set to 1. When we assign test1 to test2, only a pointer value is assigned, and the retainCount value of the object is not modified. Therefore, the reference count remains unchanged and is still 1.

Test cases:

1 Engine * engine1 = [Engine new]; 2 NSLog (@ "create an object engine1 through the new message :"); 3 // output the engine1 pointer address 4 NSLog (@ "engine1 address is % p. ", engine1); 5 // output engine1 retainCount 6 NSLog (@" engine1 retainCount is % lu ", (unsigned long) [engine1 retainCount]); 7 8 Engine * engine2 = engine1; 9 NSLog (@ "copy the pointer engine1 to the pointer engine2 :"); 10 // output the engine2 pointer address 11 NSLog (@ "engine2 address is % p. ", engine2); 12 // output engine1 retainCount13 NSLog (@" engine1 retainCount is % lu ", (unsigned long) [engine1 retainCount]); 14 // output engine2 retainCount15 NSLog (@ "engine2 retainCount is % lu", (unsigned long) [engine2 retainCount]); 16 17 Engine * engine3 = [engine1 retain]; 18 NSLog (@ "Get engine3:" Through retain message); 19 // output engine3 pointer address 20 NSLog (@ "engine3 address is % p. ", engine3); 21 // output engine1 retainCount22 NSLog (@" engine1 retainCount is % lu ", (unsigned long) [engine1 retainCount]); 23 // output engine2 retainCount24 NSLog (@ "engine2 retainCount is % lu", (unsigned long) [engine2 retainCount]); 25 // output engine3's retainCount26 NSLog (@ "engine3 retainCount is % lu", (unsigned long) [engine3 retainCount]); 27 28 [engine2 release]; 29 NSLog (@ "Send message release to engine2"); 30 NSLog (@ "engine2 address is % p. ", engine2); 31 NSLog (@" engine2 retainCount is % lu. ", (unsigned long) [engine2 retainCount]);

The output result is as follows:

The following conclusions can be drawn from the output:

Because the output reference count is required, ARC is not used, so there is a small problem, that is, when you exit the local environment, even if the object pointed to by the local pointer has been destroyed, the value of the local pointer variable remains unchanged. Therefore, you must manually assign a value to nil. If ARC is used, the memory is automatically reclaimed and the pointer is assigned to nil.

Summary

No matter whether you use pointer assignment or retain or copy to keep the object, the number of pointers pointing to the object is increased. These pointers all point to the same memory address, because the memory address allocated by the object remains unchanged.

The number of pointers to an object does not have any relationship with the reference count, but the reference count of an object can be changed through retain, copy, or release.

Only when the reference count is 0 will the memory space occupied by the object be released.

Ah, it's really a "heartless", even if more Pointers "fall in love with objects", people will only recognize reference counts in their lives.


Objective-c reference count

MyStr1 myStr2 is a constant string pointing directly to the static Zone

MyStr3 is automatically released

The two forms of retainCount are untrusted, and you should not pay attention to them.
This method of generating strings does not require memory management.

Only the initWithString generated by alloc requires manual release.
The above Code has no practical significance. Although NSString is generated as a class object, it is special to manage the memory of other oc objects, if you do not know about NSString, it will make your understanding of the reference count more confusing.
If you have no special requirements, do not check the retaincount of the string. It is meaningless. You do not know which code you want to teach.

Reference count in Objective-C

Is the reference count of the object pointed to by the pointer
As long as the Pointer Points to the same address, the reference count is the same
In your example, after the second sentence is executed, the reference count of obj2 is the same as that of obj1.
After the third sentence is executed, obj1 is changed to 2 and obj2 is also changed to 2.

You can view the reference count by calling the retainCount of the object, e.g.
NSLog (@ "% d", [obj2 retainCount]);

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.