Working principle of Memory Management in iOS Development Guide

Source: Internet
Author: User

Let's start from the following: how the object is destroyed when the garbage collection is disabled. In this context, Cocoa and Objective-C select an automatic, policy-driven process to keep the existence of objects and destroy them when they are no longer needed.

This process and policy depend on the reference count concept. Each Cocoa object carries an integer to indicate the number of other objects of interest to its existence. This integer is called the retain count ("retain" is used to avoid overlap with the term "reference ). When you create an object, or use a class factory method or alloc or allocWithZone: class method, Cocoa does some important things:

It sets the unique public member variable of the isa pointer-NSObject class of the object-to point to the class of the object, so that the object is integrated into the runtime View class hierarchy. (Refer to Object Creation "Object Creation" for more information)

It sets the retain count of an object-a hidden member variable managed by the runtime-to 1. (Assume that the creator of an object is interested in its existence)

After an object is allocated, you usually set its member variables to a reasonable initial value. (NSObject declares the init method as the prototype for this purpose ). This object can be used now; you can send a message to it and pass it to other objects.

Note: because an initiator can return an object that is not explicitly declared, the Convention is that the nested alloc message expression is in the init message (or another initiator)-for example:

 
 
  1. <code>id anObj = [[MyClass alloc] init];</code> 

When you release an object-that is, send a release message to it-NSObject to reduce its retention. If the number of reserved items changes from 1 to 0, the object will be released. Release is divided into two steps. First, the dealloc method of the object is called to release the member variables and dynamically release the allocated memory. Then, the operating system destroys the object itself and recycles the memory occupied by the object.

Important: You should never directly call the dealloc method of an object.

If you don't want an object to disappear immediately? If you send a retain message to an object when receiving it from another place, the retain count of this object is increased to 2. Two release messages are required before release. Figure 2-4 illustrates this relatively simplified scenario.

Figure 2-4 lifecycle of an object-Simplified View

Of course, in this scenario, the creator of an object does not need to keep this object. It already owns this object. However, if the Creator transmits this object to another object in a message, the situation changes. In an Objective-C program, an object that receives some other objects is always assumed to be valid within the obtained range. This receiving object can send messages to accepted objects and other objects. This assumption requires sending an object to run without releasing it too early, when a customer object has a reference pointing to it.

If the customer object wants to keep it out of the access range of the received object program, you can retain it-that is, send a retain message to it. Keep an object to increase its retention count, and thus express a ownership of the object. This customer object assumes that it is a responsibility to release the object later. If the creator of an object releases it, but a customer object retains the same object, the object remains there until the customer releases it. Figure 2-5 illustrates the order:

Figure 2-5 keep a received object

Instead of retaining an object, you can copy it by sending a copy or copyWithZone: Message. (Many subclasses, if not the majority, encapsulate some data that adopts or complies with this Protocol ). Copying an object not only copies it but often resets its retention count to 1 (see Figure 2-6 ). Copy can be a shallow copy or a deep copy, depending on the nature of the object and its intended use. A deep COPY Copies an object that can share the same role of member variables, while a shallow copy only adds references to these member variables.

When talking about usage, the difference between a copy and a retain is that the former claims the independent right to use this object; the new owner can change this copy object without worrying about its original object. In general, you copy an object instead of retaining it. When it is a numeric object-that is, an object encapsulates some basic data (such as integers ). In particular, this object itself is variable, such as an NSMutableString. For non-mutable objects, copy and retain can be equivalent and may be implemented in a similar way.

Figure 2-6 copy a received object

You may have noticed a potential problem with this mechanism regarding object lifecycle management. The Creator object that creates an object and passes it to another object does not always know when the created object can be safely released. There may be multiple references to this object in the stack, some of which are unknown to the Creator object. If the Creator object releases the created object and other objects send messages to the destroyed object, the program will crash. To eliminate this problem, Cocoa introduces a delayed release mechanism called autoreleasing.

Autoreleasing uses the autorelease pools class ). A self-release pool is a set of objects with a clearly defined range. This range marks the final release time. The Auto Release pool can be nested. When you send an autorelease message, a reference to this object is put into the nearest Auto Release pool. It is still a valid object, so other objects within the defined scope of the custom release pool can send messages to it. When the program is executed to the end of the range, the pool is released and, accordingly, all objects in the pool will be released (see Figure 2-7 ). If you are developing an Application, you may not need to create an Auto Release pool because the Application Kit automatically creates an Auto Release pool with a range of Application event cycles.

Figure 2-7 An Auto Release pool

IPhone OS prompt: Because in iPhone OS, applications run in a more memory-constrained environment, therefore, you are not encouraged to use an Auto Release pool (for example, loop) in methods or code segments for creating many objects in an application ). Instead, you should explicitly release objects whenever possible.

So far, the discussion on Object lifecycle has focused on the object management mechanism throughout the cycle. However, an object owner policy guides you how to use these mechanisms. This policy can be summarized as follows:

If you create an object (such as [[MyClass alloc] init]) by allocating and initializing the object, you will own the object and release it. This rule also applies to the use of NSObject simple method (convenient method) new.

If you copy an object, you will have the Copied object and release it.

If you retain an object, you have the ownership of the part of the object and release it when you don't need it.

On the contrary, if you receive an object from other objects, you do not own this object and should not release it. (This rule has a few exceptions that have been explicitly marked in Reference Documents)

Like any rule set, there are some exceptions and known issues ("gotchas "):

If you create an object (such as NSMutableArray arrayWithCapacity: Method) using the class factory method, assume that the object you receive is automatically released. You should not release this object on your own and rekeep it if you want to keep it.

To avoid circular reference, a child object should never retain its parent object. (A parent object is the creator of this Sub-object or an object that contains this sub-object as a member variable .)

Note: "Release" in the above Guide means to send a release message or an autorelease message to an object.

If you do not follow this ownership policy, two bad things may happen in your application. Because you have not released the created, copied, or retained objects, your application will have memory leakage. Or your program crashes when you send messages to an object that has been released from other places. There is also a warning: Debugging these problems takes time and effort.

Archiving is another basic event that may occur in the lifecycle of an object ). Archive converts the network of objects associated with an object-oriented program-object graph-into a persistent format (usually a file), saving the relationship between the identifier and the object in each graph. When a program is archived, its object map is rebuilt from the archive. To participate in archiving (archive), an object must be encoded (and decoded ). Its member variables use the NSCoder class method. NSObject uses the NSCoding protocol for this purpose.

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.