Iphone (object-c) Memory Management (2) Memory Management Policy

Source: Internet
Author: User

Now I am engaged in iphone development. I have never been very familiar with the object-c memory management mechanism. I can see that apple's official documents are well written and I have not found any translation articles. So I translated it by the way when I was learning it. My English is not very good, and the ability to organize words is even better. I hope you can point out the poor reading, I shall correct the translation in the future. For the first translation, you are welcome to shoot bricks. Don't beat me to death !!!

The words LPSTUDY in the article indicate that they are my personal understanding and may be incorrect. Please kindly advise.

Original article URL:

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH

Blog address:

Http://blog.csdn.net/lipeng08/article/details/7702707

Memory Management Policy

Under the reference counting mechanism, you can use the NSObject protocol method and standard method naming conventions for memory management. NSObject also defines a dealloc method, which is automatically triggered when the object is released. This article describes all the basic memory management rules you need to understand in Cocoa, and provides some instances for you to use it correctly.

 

Basic memory management rules

The memory management model is based on the object owner. Any object may have one or more. As long as an object has at least one owner, it will continue to exist. If there is no owner, it will be automatically released. Therefore, you need to determine when you own an object and when you no longer own it. Cocoa complies with the following conventions:

·You have your own object

You can create an object by using methods such as "alloc", "new", "copy", or "mutableCopy.

·You can use retain to obtain the object ownership.

Will not translate: Areceived object is normally guaranteed to remain valid within the method it was written in, and that method may also safely return the object to its invoker. you can use retain in two cases, (1) in the access method or init method, in order to assign values to your data. (2) Some other side effects of operations may cause your object to become invalid. In this case, you need to call the retain operation (
Explained in "AvoidCausing Deallocation of Objects You're Using ")

·When you no longer use an object, give up its ownership.

You can release the ownership of an object by sending the release or autorelease message. In cocoa terms, dropping the ownership of an object means "releasing" an object

·When you no longer have an object, you cannot release it.

This is consistent with the preceding statement.

 

 

Simple Example

To demonstrate the rules, take a look at the following code snippet

{

Person * aPerson = [[Person alloc] init];

//...

NSString * name = aPerson. fullName;

//...

[APerson release];

}

 

By using the alloc method, the Person object is createdSo when it is no longer used, it then calls the release method. The Person name does not use any method to obtain ownership, so it does not call releaseMethod. Note: This example uses release instead of autorelease.

 

Use autorelease to send delayed release messages

When you need to send delayed release messages, you can use autorelease. Typically, you need to return an object from a method. For example, you can implement the fullName method as follows:

-(NSString *) fullName {

NSString * string = [[NSString alloc] initWithFormat: @ "% @",

Self. firstName, self. lastName] autorelease];

Return string;

}

You own this string by calling the alloc method. To comply with the memory management rules, you must release the ownership of the string before you lose access to the string. If you use the release method, the string will be released before it is returned. by using autorelease, you indicate that you want to release the ownership, but you allow the caller of the method to use the returned string before it is released.

 

You can also implement the fullName method as follows::

-(NSString *) fullName {

NSString * string = [NSString stringWithFormat: @ "% @",

Self. firstName, self. lastName];

Return string;

}

 

Follow the Basic Rules. By calling stringWithFormat, you do not have a string. Therefore, you can safely return a string from the method.

 

For comparison, the following implementation is incorrect

-(NSString *) fullName {

NSString * string = [[NSString alloc] initWithFormat: @ "% @",

Self. firstName, self. lastName];

Return string;

}

Through naming conventions, the caller of fullName has undoubtedly returned strings, but the caller has no reason to release the returned string, so the memory occupied by the string is leaked.

 

You do not have the ownership of the referenced object returned.

Some methods in cocoa are returned by referencing (that is, they pass such a parameter ClassName ** or id *). A common mode is to use the NSError object to return detailed error information, such as initWithContentsOfURL: options: error: (NSData) andinitWithContentsOfFile: encoding: error: (NSString ).

 

In these cases, the rules described above still apply. When you trigger any of their methods, you have not created an NSError object, so you do not have it and you do not need to release it. Example:

NSString * fileName = <# Get a file name #>;

NSError * error = nil;

NSString * string = [[NSString alloc] initWithContentsOfFile: fileName

Encoding: NSUTF8StringEncoding error: & error];

If (string = nil ){

// Deal with error...

}

//...

[String release];

 

 

Dealloc implementation for releasing the owner object

NSObject defines a dealloc method. When an object has no owner and its memory is recycled, The dealloc method is automatically triggered. The Dealloc method is used to release the object's memory and arrange its resources. Of course, this includes its instance variables.

 

The following example shows how to use the dealloc method in the Person class.

@ Interface Person: NSObject {}

@ Property (retain) NSString * firstName;

@ Property (retain) NSString * lastName;

@ Property (assign, readonly) NSString * fullName;

@ End

 

@ Implementation Person

@ Synthesize firstName = _ firstName, lastName = _ lastName;

//...

-(Void) dealloc

[_ FirstName release];

[_ LastName release];

[Super dealloc];

}

@ End

 

Attention:

· You never need to trigger the dealloc method of another object.

· At the end of your dealloc implementation, you must trigger the dealloc method of the base class

· You should not bind system resource management and object lifecycle together. See "Don't Usedealloc to Manage Scarce
Resources.

· When the program is terminated, the object may not trigger the dealloc method. When the program exits, the memory occupied by the program is automatically cleared. Therefore, it is more effective to allow the operating system to clear resources by itself than to simply trigger the memory management method.

 

Core Foundation uses similar but different rules

For Core Foundation, there are similar memory management rules (seeMemoryManagement Programming Guide
Core Foundation
). However, The naming rules for Cocoa and Core Foundation are different, especially for The creation of CoreFoundation (see"
CreateRule "inMemoryManagement Programming Guide for Core Foundation)

The rule does not apply to methods that return object-c objects. For example, in the following code snippet, you do not need to release the ownership of myInstance.

MyClass * myInstance = [MyClass createInstance];

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.