Introduction to objective-C Memory Management

Source: Internet
Author: User

I. Preface

For most people who have switched from C ++ or Java to learn object-C (hereinafter referred to as OC), the language OC looks strange and troublesome to use.

OC does not have the same garbage collection mechanism as Java. That is to say, OC programming requires programmers to manually manage the memory. This is why it is annoying. Apple has always promoted developers to write the optimal code within limited hardware resources, with the Minimum CPU usage and the minimum memory usage.

 

Ii. Basic Principles

Object creation:

When the OC creates an object, it does not directly return this object, but returns a pointer to the object. In addition to the basic type, we basically use pointers in the OC.

Classa * A = [[classa alloc] init];

When [classa alloc] is sent, the Message notification system allocates memory space for the classa object and returns a pointer to the uninitialized object.

The uninitialized classa object takes over the init message. init returns a pointer to the initialized classa object and assigns it to variable.

When creating and using an object, you must manually release the object.

[A dealloc];

If both pointer A and pointer B point to the same memory address in the heap

Classa * A = [[classa alloc] init];

Classa * B =;

[A dealloc];

When the execution reaches the third row, pointer B becomes a headless pointer. This is a common error in C ++. We need to avoid this type of error because headless pointers are dangerous.

Reference count:

OC uses retain count in memory management, and stores a number inside the object to indicate the number of times referenced. Init, new, and copy all add 1 to retain count. When an object is destroyed, the system does not directly call the dealloc method. Instead, it first calls release to reduce retain count by 1. When retain count is equal to 0, the system will call the dealloc method to destroy the object.

During pointer assignment, retain count does not automatically increase. To avoid the preceding errors, we need to manually retain the value once to increase retain count by 1.

Classa * A = [[classa alloc] init]; // retain COUNT = 1

Classa * B =;

[B retain]; // retain COUNT = 2

[A dealloc];

In this way, when the fourth row is executed, the retain count of the object is reduced by 1 and is not destroyed. The pointer B is still valid.

 

Memory leakage:

As shown in the preceding column, when a classa object is generated, pointer A has access to this object. If you lose access to an object without reducing the retain count to 0, memory leakage will occur. That is to say, the allocated memory cannot be recycled.

Classa * A = [[classa alloc] init];

A = nil;

 

Iii. autorelease pool

To facilitate programmer Management of memory, Apple introduced the autorelease pool in OC ). Objects can be automatically released when some rules are followed. However, even with such a tool, the OC memory still requires the programmer's attention at all times (this automatic release pool is not the same as the Java garbage collection mechanism, or the horse riding cannot catch up with the Java mechanism, may not even be able to eat dust ).

Classa * A = [[classa alloc] init] autorelease];

// Retain COUNT = 1, but release is not required

Principles of autorelease pool:

Autorelease pool is a class in OC. Autorelease pool is not inherent. You need to manually create it.

NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];

Generally, when you create an iPhone project, xcode automatically creates an autorelease pool for you, which is written in the main function.

A variable array is included in the NSAID utoreleasepool to store objects declared as autorelease. When the NSAID utoreleasepool itself is destroyed, it traverses this array and each member in the release array (note that this is only release, and the object is not directly destroyed ). If the retain count of a member is greater than 1, the object is not destroyed, causing memory leakage.

By default, there is only one nutoreleasepool. You can create an nutoreleasepool in your program. Objects marked as autorelease will match the latest nutoreleasepool. NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];

// Create some objects

// Do something...

[Pool release];

You can also use the NSAID utoreleasepool nested, just as you use for nested.

Even though the NSAID utoreleasepool does not seem as cumbersome as manual release, it is not recommended to use the NSAID eleasepool to manage the memory. This is because if a large number of objects are marked as autorelease In An NSAID utoreleasepool, the memory will increase during the running of the program until the NSAID utoreleasepool is destroyed. If there are enough objects, you may receive a low memory warning or crash during the running process.

 

Autorelease pool extension:

If you are curious, delete the NSAID utoreleasepool code in the main function, and declare the object as autorelease in your own code, you will find that the system will not send you an error message or warning. If you use a memory detection tool to detect the memory, you may be surprised to find that your object is still destroyed.

In fact, when a new run loop is generated, the system will automatically create an NSAID utoreleasepool, which cannot be deleted.

 

Do not use nsstring for memory testing. OC performs special processing on strings

Nsstring * STR = [[nsstring alloc] stringwithstring: @ "123"];

When outputting STR retain count, you will find that retain count is greater than 1.

 

4. Manual Memory Management

Use alloc, new, and copy to create an object. The retain count of this object is equal to 1. You need to use release to release this object. Who created and who released it. Objects Created by methods other than these three minutes are declared as autorelease by default.

Classa * A = [[classa alloc] init];

Classa * B =;

[B retain];

// Do smoething

[B release];

B = nil;

When a pointer is assigned to another pointer, the number of references to the object pointed to by pointer A does not increase. That is to say, the retain count of the object is still equal to 1. Only after retain is reached will retain count be incremented by 1. If [A release] is executed at this time, but the pointer gives up access to the object, the retain count of the object is reduced by 1, and the object is not destroyed. The object will be destroyed only after B executes the release method. Therefore, whoever retakes, who needs release.

After the object is destroyed, the pointer still exists. So after release, it is best to leave the pointer blank to prevent the emergence of headless pointers. By the way, release is legal as a null pointer, but nothing will happen.

If you create and return an object in a function, you need to declare this object as autorelease.

(Classa *) function ()

{

Classa * A = [[classa alloc] init] autorelease];

Return;

}

Otherwise, memory leakage may occur.

 

V. Attribute and Memory Management

Apple has never stressed that retain in attributes. In fact, attributes with retain may have been retain once in the merged setter during the assignment. Therefore, release is also required here.

@ Property is actually getter and setter, and @ synthesize is the synthesis method. Why can I use "." To directly call member variables after declaring attributes? This is because after the attribute is declared, the system combines a set method and a get Method Based on the attribute you have given. Using "." is not directly related to attributes. If you are not bothered, you can use "." To call variables by writing more set and get methods in your program.

@ Property (). If you do not write anything in it, the system will set your attribute:

@ Property (atomic, assign ).....

Nonatomic:

This attribute does not have the corresponding atomic keyword. Even if I write it like this, the system defaults the atomic only when you do not declare this feature. You cannot manually declare this feature.

If your program has only one main thread, or you are sure that your program will not access the same variable when two or more threads are running, you can declare it as nonatomic. Specify the nonatomic feature. The Compiler does not consider thread security issues when merging accessors. If multiple threads access this variable at the same time, you can declare the feature as atomic (by omitting the keyword nonatomic ). In this state, the editor adds a lock (@ synchronized) to the accessor when merging accessors. At the same time, only one thread can access the variable.

However, the use of locks requires a price. An Attribute declared as atomic is slower to set and obtain this variable than the attribute declared as nonatomic. So if you don't want to write multi-threaded code, you 'd better declare the attribute feature of the variable as nonatomic.

About assign, retain, and copy:

Assign is the default attribute feature of the system. It applies to almost all variable types of OC. For non-object variables, assign is unique and optional. However, if you declare an object type variable as Assign Under the reference count, you will receive a warning from the compiler during compilation. Because assign creates only one weak reference for the object feature under the reference count (that is, the shortest copy ). It is dangerous to use variables in this way. When you release the previous object, the assigned object pointer becomes a headless pointer. Therefore, when declaring attributes for Object-type variables, use assign as few as possible (or not.

The setter of assign synthesis looks like this:

-(Void) setobja :( classa *)

{

Obja =;

}

 

Before going into retain, write the setter declared as retain:

-(Void) setobja :( classa *)

{

If (obja! =)

{

[Obja release];

Obja =;

[Obja retain]; // The retain count of the object plus 1

}

}

Obviously, in the setter of retain, the variable retain once, even if you are in the program

Self. obja =;

After writing such a statement, obja still needs to release the object to ensure that the retain count of the object is correct. However, if your code

Obja =;

If you only write such a statement, we only perform a shallow copy and the retain count of the object is not added. Therefore, you do not need to release the object obja.

The difference between the two statements is that the first sentence uses the setter generated by the compiler to set the obja value, while the second sentence is just a simple pointer assignment.

 

The setter of copy looks like this:

 

-(Void) setobja :( classa *)

{

Classa * temp = obja;

Obja = [A copywithzone: Nil];

[Temp release];

}

Copy must be implemented through copywithzone: This method, because the secondary copy feature only applies to the type that owns this method, that is, this class must support replication. Replication removes the original object release and points the pointer to a new copy of the object. Therefore, even if you release the original object in the setter, you still need to release the new object (copy) to which the release points ).

 

 

Vi. Conclusion

The only memory management method currently available for iOS development is reference count, whether you like it or not. On a machine with insufficient memory, you can only step by step when writing a program, try to free up memory space for your program, and ensure that the system will not give you a warning. Even if Apple adds another memory management method (spam) to Mac OS X snow leopard (v10.5), it is not applicable to IOS.

 

 

 

I have created a QQ group: 57636364 new users can join! Hesoft lezhi Institute csdn Bailu

Source: http://www.cnblogs.com/cnbailu/archive/2012/04/28/2475529.html

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.