Oc memory management mechanism and oc Memory Management

Source: Internet
Author: User

Oc memory management mechanism and oc Memory Management

I have always been familiar with the oc memory management mechanism. Today I read the official documentation to record it.

I am relatively lazy. I am posting official documents here.

//************************//

Use Accessor Methods to Make Memory Management Easier

If your class has a property that is an object, you must make sure that any object that is set as the value is not deallocated while you're using it. you must therefore claim ownership of the object when it is set. you must also make sure you then relinquish ownership of any currently-held value.

Sometimes it might seem tedious or pedantic, but if you use accessor methods consistently, the chances of having problems with memory management decrease considerably. if you are using retain and release on instance variables throughout your code, you are almost certainly doing the wrong thing.

Consider a Counter object whose count you want to set.

@ Interface Counter: NSObject
@ Property (nonatomic, retain) NSNumber * count;
@ End;
The property declares two accessor methods. Typically, you shocould ask the compiler to synthesize the methods; however, it's instructive to see how they might be implemented.

In the "get" accessor, you just return the synthesized instance variable, so there is no need for retain or release:

-(NSNumber *) count {
Return _ count;
}
In the "set" method, if everyone else is playing by the same rules you have to assume the new count may be disposed of at any time so you have to take ownership of the object-by sending it a retain message- to ensure it won't be. you must also relinquish ownership of the old count object here by sending it a release message. (Sending a message to nil is allowed in Objective-C, so the implementation will still work if _ count hasn't yet been set .) you must send this after [newCount retain] in case the two are the same object-you don't have want to inadvertently cause it to be deallocated.

-(Void) setCount :( NSNumber *) newCount {
[NewCount retain];
[_ Count release];
// Make the new assignment.
_ Count = newCount;
}

/*************************************** *********/

Simply put, it is the @ {get, set} method. The get method is not mentioned. Let's talk about the set method.

-(Void) setCount :( NSNumber *) newCount {
[NewCount retain]; // newCount reference count + 1
[_ Count release]; // count the reference of the object pointed to by the _ count pointer-1. If this sentence is not added, memory leakage will occur.
// Make the new assignment.
_ Count = newCount; // simple pointer assignment
}

 

/***************************************/

The second uses a convenience constructor to create a new NSNumber object. There is therefore no need for retain or release messages

-(Void) reset {
NSNumber * zero = [NSNumber numberWithInteger: 0];
[Self setCount: zero];
}
Note that both use the set accessor method.

The following will almost certainly work correctly for simple cases, but as tempting as it may be to eschew accessor methods, doing so will almost certainly lead to a mistake at some stage (for example, when you forget to retain or release, or if the memory management semantics for the instance variable change ).

-(Void) reset {
NSNumber * zero = [[NSNumber alloc] initWithInteger: 0];
[_ Count release];
_ Count = zero;
}
Note also that if you are using key-value observing, then changing the variable in this way is not KVO compliant.

/*************************************** *******************/

This is a reset method officially written. In simple terms, the reference count of objects referenced by alloc is + 1, so release is required when it is not needed,

[NSNumber numberWithInteger: 0]; In this method, the reference count is not greater than 1, so release is not required when you do not need it,

As for how internal implementation is implemented, this article will not study it.

/*************************************** *********************/

 

Don't Use Accessor Methods in Initializer Methods and dealloc
The only places you shouldn't use accessor methods to set an instance variable are in initializer methods and dealloc. to initialize a counter object with a number object representing zero, you might implement an init method as follows:

-Init {
Self = [super init];
If (self ){
_ Count = [[NSNumber alloc] initWithInteger: 0];
}
Return self;
}

/*************************************** *********************/

This is important. In the class initialization method, methods like self. count cannot be implemented, because self. count = 1 is similar;

In my opinion, this init () method can be completely created only when the returned class is returned.

Self. count is equivalent to self. getcount (); this method may be overloaded, making the result unpredictable. // * Note: if any error occurs, please correct it.

In any case, this should be our design principle.

/*************************************** *********************/

Use Weak References to Avoid Retain Cycles

Retaining an object creates a strong reference to that object. an object cannot be deallocated until all of its strong references are released. A problem, known as a retain cycle, can therefore arise if two objects may have mathematical references-that is, they have a strong reference to each other (either directly, or through a chain of other objects each with a strong reference to the next leading back to the first ).

The object relationships shown in Figure 1 into strate a potential retain cycle. the Document object has a Page object for each page in the document. each Page object has a property that keeps track of which document it is in. if the Document object has a strong reference to the Page object and the Page object has a strong reference to the Document object, neither object can ever be deallocated. the Document's reference count cannot become zero until the Page object is released, and the Page object won't be released until the Document object is deallocated.

The solution to the problem of retain cycles is to use weak references. A weak reference is a non-owning relationship where the source object does not retain the object to which it has a reference.

To keep the object graph intact, however, there must be strong references somewhere (if there were only weak references, then the pages and paragraphs might not have any owners and so wocould be deallocated ). cocoa establishes a convention, therefore, that a "parent" object shocould maintain strong references to its "children," and that the children shocould have weak references to their parents.

So, in Figure 1 the document object has a strong reference to (retains) its page objects, but the page object has a weak reference to (does not retain) the document object.

Examples of weak references in Cocoa include, but are not restricted to, table data sources, outline view items, notification observers, and miscellaneous targets and delegates.

You need to be careful about sending messages to objects for which you hold only a weak reference. if you send a message to an object after it has been deallocated, your application will crash. you must have well-defined conditions for when the object is valid. in most cases, the weak-referenced object is aware of the other object's weak reference to it, as is the case for circular references, and is responsible for policying the other object when it deallocates. for example, when you register an object with a notification center, the notification center stores a weak reference to the object and sends messages to it when the appropriate notifications are posted. when the object is deallocated, you need to unregister it with the notification center to prevent the notification center from sending any further messages to the object, which no longer exists. likewise, when a delegate object is deallocated, you need to remove the delegate link by sending a setDelegate: message with a nil argument to the other object. these messages are normally sent from the object's dealloc method.

/*************************************** *********************/

In a simple explanation, we must all understand retain, assign, weak, and strong. But when should we use any references?

First, the official document illustrates A situation where A references B and B references C. In this case, A closed loop is formed, and the memory cannot be released. What should I do at this time?

The official solution is to use weak and strong to solve it. Only the root attribute adopts strong description, and weak is used to describe sub-attributes, which can solve the problem of circular reference. In short, the strong attribute will increase the reference count by 1, but the weak will not. This will not cause circular reference.

/*************************************** ***********************/

Ownership Policy Is Implemented Using Retain Counts

The ownership policy is implemented through reference counting-typically called "retain count" after the retain method. Each object has a retain count.

When you create an object, it has a retain count of 1.
When you send an object a retain message, its retain count is incremented by 1.
When you send an object a release message, its retain count is decremented by 1.
When you send an object a autorelease message, its retain count is decremented by 1 at the end of the current autorelease pool block.

If an object's retain count is already CED to zero, it is deallocated.

Important: There shocould be no reason to explicitly ask an object what its retain count is (see retainCount ). the result is often misleading, as you may be unaware of what framework objects have retained an object in which you are interested. in debugging memory management issues, you should be concerned only with ensuring that your code adheres to the ownership rules.

/*************************************** ***********************/

This is the principle of referencing the counting design. Apple specifically stated that you only need to abide by these Rules. Any method that tries to print the currently referenced counting is required, the result may be incorrect.

There are other details, so I will not repeat them here.

To sum up, the reference count is divided into three categories:

1. assign

2. copy

3. retain (including weak and strong used to solve the circular reference problem)

 

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.