IOS development diary 53-ARC and memory management, ios diary 53-arc

Source: Internet
Author: User

IOS development diary 53-ARC and memory management, ios diary 53-arc

Today, the blogger has a requirement for memory management and has encountered some difficulties. I would like to share with you the hope to make common progress.

Because the memory of mobile devices is limited, we need to strictly manage the memory to avoid wasting resources due to memory leakage. In OC,Only objects belong to the memory management scope. For example, basic data types such as int and struce do not have the concept of memory management. In iOS development, memory management is actually the management of reference counters.

Three methods of automatic garbage collection for OC Memory Management

In OC2.0, there is an automatic garbage collection memory management mode. through automatic garbage collection, the system can automatically detect whether the object has other objects. During the program running, objects that are not referenced are automatically released.
Note:Automatic garbage collection is not supported in the iOS runtime environment and is only supported in the OS X environment. However, Apple does not recommend this method, but rather ARC is recommended for replacement.

Manual reference of counter (MRC) and automatic release of pool; reference of counter Concept

As the name implies, the reference counter isThe number of times an object is referenced (used). Each object's reference counter occupies 4 bytes..
As shown in, when using A to create an object, the RC of the object is 1 by default. When B points to the object, the RC + 1 of the object is 2. Then when the pointer does not point to the object, the object's RC-1 = 2-1 = 1. Finally, when B does not point to the object, the object's RC-1 = 1-1 = 0, the object is destroyed.
Note: When an object is created, the RC value of the object is 1 by default. When the object is referenced once, you need to call the retain method so that the RC value is + 1; when the pointer loses its reference to this object, you need to call the release method to make the RC value-1. When RC = 0, the object is automatically destroyed and recycled by the system.

Manual reference counter (MRC)

MRC is used to control the increase and decrease of the reference counter manually. The methods that affect the object RC are as follows:

// Book class description and implementation @ interface Book: NSObject @ end @ implementation Book @ end // Peron class description and implementation @ interface Person: NSObject {Book * _ book ;} -(void) setBook :( Book *) book; @ end @ implementation Person-(void) setBook :( Book *) book {if (_ book! = Book) {// if the newly set book object is not the book object that was previously pointed to [_ book release]; // make the RC-1 of the previous object _ book = [book retain]; // currently referenced RC + 1}-(void) dealloc // reload the dealloc method to destroy the object {[_ book release]; // because _ book controls the Book object, _ book calls the release method to make the RC-1 [super dealloc]; // call the dealloc method of the parent class, and it must be placed in the last row }}@ end // main function test void main () {Book * B = [Book new]; Person * p = [Person new]; p. book = B; [B release]; // B controls the Book object, B calls the release method to make RC-1 [p release]; // p controls the Person object, p call the release method to make RC-1}

The code above shows that the set value and value methods of the member variables are manually generated, and the reference counter of the member variables in the setter method is also manually set. We can also use@ PropertyAnd the corresponding keywords are generated by the compiler.
The @ property keyword in MRC is as follows:
1. assign, retain, and copy
These keywords are used for memory management of the setter method. If assign is used (generally for non-OC objects), the value assignment operation is executed directly. If retain is used (generally for OC objects ), the new value of retain and the old value of release are used. If copy is used, the old value of release and the new value of copy are used. Do not show useAssign is the default value..
2. nonatomic and atomic
These two keywords are used for multi-thread management. nonatomic has high performance and atomic has low performance. Do not show useAtomic is the default value..
3. readwrite and readonly
The two keywords are used to indicate whether to generate the setter method. readwrite will automatically generate the setter and getter methods. readonly will only generate the getter method. Do not show useReadwrite is the default value..
4. getter and setter
These two keywords are used to give another name to the set value and the value method. For example, @ property (getter = a, setter = B :) int age; equivalent to the value method named a and the value method named B :.
If the @ property attribute is used, the code above can be changed:

// Book class description and implementation @ interface Book: NSObject @ end @ implementation Book @ end // Peron class description and implementation @ interface Person: NSObject-(void) dealloc; @ property (nonatomic, retain) Book * _ book; @ end @ implementation Person-(void) dealloc // reload the dealloc method to destroy the object {[_ book release]; // used for _ book to control the Book object, _ book calls the release method to make the RC-1 [super dealloc]; // call the dealloc method of the parent class, and it must be placed in the last line} @ end // main function test void main () {Book * B = [Book new]; Person * p = [Person new]; p. book = B; [B release]; // B controls the Book object, B calls the release method to make RC-1 [p release]; // p controls the Person object, p call the release method to make RC-1}
Memory Management Principles for loop reference

When two classes A contain B and B contains A circular referenceSee the following code:

// Book1 class description and implementation @ interface Book1: NSObject @ property (nonatomic, retain) Book2 * _ book2;-(void) dealloc; @ end @ implementation Book1-(void) dealloc // reload the dealloc method to destroy the object {[_ book2 release]; // used for _ book to control the Book object, _ book to call the release method to make the RC-1 [super dealloc]; // call the dealloc method of the parent class, which must be placed in the last line} @ end // Book2 class declaration and implementation @ interface Book2: NSObject @ property (nonatomic, retain) book1 * _ book1;-(void) dealloc; @ end @ implementation Book2-(void) dealloc // reload the dealloc method to destroy the object {[_ book1 release]; // used for _ book to control the Book object, _ book calls the release method to make the RC-1 [super dealloc]; // call the dealloc method of the parent class, and it must be placed in the last line} @ end // main function test void main () {Book1 * b1 = [[Book1 alloc] init]; book2 * b2 = [[Book2 alloc] init]; b1.book2 = b2; b2.book1 = b1; [b1 release]; [b2 release];}

The following analyzes the main function code. When Book1 * b1 = [[Book1 alloc] init] is executed, b1 points to book1. When Book2 * b2 = [[Book2 alloc] init] is executed, b2 points to Book2. When b1.book2 = b2 is executed, the member Variable _ b2 of Book1 points to Book2. After b2.book1 = b1 is executed, the member Variable _ b1 of Book2 points to book1. Shows the specific relationship in the memory.

In this case, the reference counter RC of Book1 is 2, and the reference counter RC of Book2 is 2.
After [b1 release] is executed, b1 releases control of Book1. In this case, the reference counter RC of Book1 is 2-1 = 1.
When [b2 release] is executed, b2 releases control of Book2. At this time, the reference counter RC of Book2 is 2-1 = 1.
As there are still pointers pointing to Book1 and Book2, the relationship between Book1 and Book2 in the memory is shown in the black elliptic. Therefore, the dealloc function will not be called, so Book1 and Book2 will not destroy sales, which causesMemory leakage.


In this case, you only need to declare the @ property attribute in Book1 and Book2. One end uses retain and one end uses assign. Change a retian in @ property (nonatomic, retain) Book1 * _ book1 or @ property (nonatomic, retain) Book2 * _ book2 to assign. Analyze the cause by yourself.

Let's look at the following circular references,Only assign can be used.

@ Interface Book: NSObject @ property (nonatomic, assign) id instance; // you must use assign-(void) dealloc; @ end @ implementation Book-(void) dealloc // reload the dealloc method to destroy the object {[_ instance release]; // used for _ book to control the Book object, _ book to call the release method to make the RC-1 [super dealloc]; // call the dealloc method of the parent class and put it in the last line} @ endvoid mian () {Book b1 = [[Book alloc] init]; book b2 = [[Book alloc] init]; b1.instance = b2; b2.instance = b1; [b1 release]; [b2 release];}

You can analyze that if @ property (nonatomic, assign) id instance; Changes assign to retain, it will also cause memory leakage.

Use of Autorelease Pool

As the name implies, autorelease Automatically releases the object without manual release. From the code above, we know that after the object obj is created in the main function, we always need to manually call the [obj release] method. This will undoubtedly increase the workload and will be meaningless to our technological growth. To reduce this meaningless work, you can use the Autorelease Pool method.
The Autorelease Pool Automatically releases the Pool. When an object in the Autorelease Pool is created, you only need to call the autorelease method, the compiler will call the final release method of the objects in the pool.

Autorelease Pool can be created in either of the following ways:

1. Create an object by @ autoreleasepool as follows: @ autoreleasepool {// you do not need to manually call the release method for the object created in braces .}
2. Create a pool using the NSAID utoreleasepool class, as shown below: NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init]; // This range is the automatic release pool [pool release];

Autorelease Pool is used as follows:

Void main () {@ autoreleasepool {Person p = [[Person alloc] init] autorelease]; // call the autorelease method // you do not need to call [p release]; method, this method is automatically called when the autoreleasepool is exceeded. }}

It is best to use the automatic release pool to release objects in the returned object method.Because the newly created object cannot be released before the object is returned, the automatic release pool can be used to delay the release of the object. The sample code is as follows:

-(Person *) getNewPerson {Person p * = [[Person alloc] init] autorelease]; // do something return p ;} or {Person p * = [[Person alloc] init]; // do something return [p autorelhing];}

Note:

Automatic Reference Counter (ARC) 

The compiler automatically controls the Object Reference Counter of ARC.
In ARC mode, the new object is usually limited by the following keywords.

In the ARC mode, the retain, release, and other methods in MRC become unavailable, because the ARC does not require manual memory management, and everything is done by the compiler.
In MRC mode, assign an object pointer to another object pointer as follows:

Person p1 = [Person new]; Person p2 = [Person new]; [p2 release] // when p2 loses control of the object, it must first releasep2 = p1; // assign values

However, in the ARC mode, we do not care about the specific operation. We only need to assign values directly:

Person p1 = [Person new]; Person p2 = [Person new]; p2 = p1; // assign values
Circular references in ARC Mode

In ARC mode, the modifier of the @ property attribute on memory management is strong and weak (retain and assign in MRC are not available), indicating whether it is declared as a strong pointer or a weak pointer. In general, strong is used for modification, but circular references are not.

In this case, one end uses strong and the other end uses weak. If strong is used for modification, the object will be recyclically maintained, resulting in Memory leakage.

// Book1 class description and implementation @ interface Book1: NSObject @ property (nonatomic, strong) Book2 * _ book2; @ end @ implementation Book1 @ end // Book2 class description and implementation @ interface Book2: NSObject @ property (nonatomic, weak) Book1 * _ book1; @ end @ implementation Book2 @ end // main function test void main () {Book1 * b1 = [[Book1 alloc] init]; book2 * b2 = [[Book2 alloc] init]; b1.book2 = b2; b2.book1 = b1 ;}

In the following example, weak can be used only. If strong is used for modification, it will cause loop persistence of the object and Memory leakage.

@ Interface Book: NSObject @ property (nonatomic, weak) id instance; // you must use assign @ end @ implementation Book @ endvoid mian () {Book b1 = [[Book alloc] init]; Book b2 = [[Book alloc] init]; b1.instance = b2; b2.instance = b1 ;}

Note:

Summary 

The essence of memory management is the operation on the object reference counter. Understanding the memory management operation in MRC mode helps us understand the OC memory management. Memory Management is only for objects. Pay attention to the selection of @ property attribute keywords under MRC and ARC. In MRC mode, OC objects usually use the retain keyword, while non-OC objects use the assign keyword, loop reference is an exception. Generally, one end uses assign and one end uses retain. In ARC mode, OC objects usually use the strong keyword, while non-OC objects use the assign keyword, loop reference is an exception. Generally, one end uses strong and the other end uses weak.

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.